問題描述
在我的一個程序中,我必須與一些使用 const char*
的遺留代碼交互.
In one of my programs, I have to interface with some legacy code that works with const char*
.
假設我有一個如下所示的結構:
Lets say I have a structure which looks like:
struct Foo
{
const char* server;
const char* name;
};
我的上層應用只處理std::string
,所以想到了用std::string::c_str()
來取回const char*
指針.
My higher-level application only deals with std::string
, so I thought of using std::string::c_str()
to get back const char*
pointers.
但是 c_str()
的生命周期是多少?
But what is the lifetime of c_str()
?
我可以在不面對未定義行為的情況下做這樣的事情嗎?
Can I do something like this without facing undefined behavior ?
{
std::string server = "my_server";
std::string name = "my_name";
Foo foo;
foo.server = server.c_str();
foo.name = name.c_str();
// We use foo
use_foo(foo);
// Foo is about to be destroyed, before name and server
}
還是我應該立即將 c_str()
的結果復制到另一個地方?
Or am I supposed to immediately copy the result of c_str()
to another place ?
謝謝.
推薦答案
如果 std::string
被銷毀或非-const 字符串的成員函數被調用.因此,如果您需要保留它,通常您會想要制作它的副本.
The c_str()
result becomes invalid if the std::string
is destroyed or if a non-const member function of the string is called. So, usually you will want to make a copy of it if you need to keep it around.
在您的示例中,c_str()
的結果似乎是安全使用的,因為在該范圍內不會修改字符串.(但是,我們不知道 use_foo()
或 ~Foo()
可能對這些值做什么;如果他們將字符串復制到別處,那么他們應該做一個真正的復制,而不僅僅是復制char
指針.)
In the case of your example, it appears that the results of c_str()
are used safely, because the strings are not modified while in that scope. (However, we don't know what use_foo()
or ~Foo()
might be doing with those values; if they copy the strings elsewhere, then they should do a true copy, and not just copy the char
pointers.)
這篇關于std::string::c_str() 結果的生命周期是多少?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!