遵守以下代码。我从std::string
C风格字符串过渡到另一个std::string
原因bmd2create
是因为它是C Binding API的一部分,因此必须采用C风格字符串。否则,我会std::string
尽可能使用。
void bmd2create(const char * filename) {
std::string sFileName (filename);
// do things with sFileName
std::ostringstream ostr;
ostr << "\t(in) filename = " << filename << "\n";
logger.log(Logger::LogLevel::LOG_DEBUG, ostr.str());
}
const char * filename = std::string(filepath + "dataset1.out").c_str();
// *filename is 46 '.'
bmd2create(filename);
// *filename is now 0 '\0'
文件名指针在何处以及为什么被移动?将其移回字符串开头的最佳方法是什么?
这条线特别没用:
const char * filename = std::string(filepath + "dataset1.out").c_str();
您创建一个临时文件std::string
,然后使用来获得指向其内容的指针c_str()
。在下一行执行之前,临时变量在完整表达式的末尾被清除。那时,指针无处可去。使用它是未定义的行为。
您认为指针在调用之前bmd2create
是可以的,原因是指向的内存尚未被覆盖。但是它不再归字符串所有,因此任何将来的分配都可以用新对象替换它。
正确的代码是:
std::string filename = std::string(filepath) + "dataset1.out";
bmd2create(filename.c_str());
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句