[英]assignment of c_str() to a string
I have a problem which i cannot fix on my own. 我有一个问题,我不能自己解决。
string filenameRaw;
filenameRaw= argv[1];
function(filenameRaw.c_str(),...);
function(const char* rawDataFile,const char* targetfieldFile,const char* resultFile,const char* filename)
...
this->IOPaths.rawData=rawDataFile;
...
works very fine so far. 到目前为止工作非常好。 Now I try to put another string in the variable IOPaths.rawData...
现在我尝试在变量IOPaths.rawData中添加另一个字符串...
function(const char* rawDataFile,const char* targetfieldFile,const char* resultFile,const char* filename)
...
string filenameRaw;
filenameRaw=reader.Get("paths", "rawData", "UNKNOWN")
...
const char* rawDataFile1=filenameRaw.c_str();
cout << "Compare: " << strcmp(rawDataFile,rawDataFile1) <<endl;
...
this->IOPaths.rawData=rawDataFile1;
this does not work any more. 这不再起作用了。 Later in my programm I get errors with the filename.
后来在我的程序中,我得到了文件名错误。 The strcmp definitly gives a 0, so the strings must be equal.
strcmp肯定给出0,所以字符串必须相等。 Does anyone has an idea what i am doing wrong?
有谁知道我做错了什么?
The validity of the output of c_str()
is limited to, at most, the lifetime of the object on which c_str()
was called. c_str()
输出的有效性最多限于调用c_str()
的对象的生命周期。 1 1
I suspect that this->IOPaths.rawData
is pointing to deallocated memory once filenameRaw
is out of scope. 我怀疑,当
filenameRaw
超出范围时, this->IOPaths.rawData
指向释放的内存。
An adequate remedy would be to pass the std::string around rather than [const] char*
. 一个适当的补救方法是传递std :: string而不是
[const] char*
。 A good stl implementation would use copy on write semantics for the string class so perhaps you wouldn't be repeatedly copying string data. 一个好的stl实现会对字符串类使用copy on write语义,所以也许你不会重复复制字符串数据。
1 In certain instances (such as if the object is modified), it could be less. 1在某些情况下(例如,如果对象被修改),它可能会更少。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.