这个char *为什么以及何时改变值
Why and when does this char * change values?
观察下面的代码。我从std::string
到C风格字符串再回到std::string
的原因是因为bmd2create
是C绑定API的一部分,它必须采用C风格字符串。否则,我将尽可能使用std::string
。
OtherFile.h
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());
}
Main.cpp
const char * filename = std::string(filepath + "dataset1.out").c_str();
// *filename is 46 '.'
bmd2create(filename);
// *filename is now 0 ' '
文件名指针被移动的位置和原因?把它移回到弦的开始的最好方法是什么?
这一行特别没用:
const char * filename = std::string(filepath + "dataset1.out").c_str();
创建一个临时的std::string
,然后用c_str()
获得一个指向其内容的指针。临时变量在完整表达式的末尾,在下一行执行之前被清理。在这一点上,指针没有移动。使用它是未定义的行为。
在调用bmd2create
之前你认为指针是ok的原因是指向的内存还没有被覆盖。但它不再为字符串所有,因此任何将来的分配都可以用新对象替换它。
正确的代码应该是:
std::string filename = std::string(filepath) + "dataset1.out";
bmd2create(filename.c_str());
相关文章:
- 何时在引用或唯一指针上使用移动语义
- 变量没有改变?通过向量的函数调用
- 何时提供默认参数作为模板参数
- C++-明确何时以及如何调用析构函数
- 如何改变c++应用程序的视觉效果
- 在以唯一ptr为值的C++映射中,动态内存何时会被销毁
- C++在不同线程中改变向量
- 如何访问和改变存储在矢量C++中的对象
- 何时应通过引用传递矢量参数而不是按值传递矢量参数?
- 在C++行尾写一个分号或多个分号是否会改变任何内容
- 如果非动态变量被指针引用,何时超出范围?
- 类作用域的类型别名"using":[何时]方法中的用法可以先于类型别名?
- 何时定义QT_NO_CONTEXTMENU?
- 为什么字符串的 move() 会改变内存中底层数据的位置?
- 为什么 c++ 动态数组的大小没有改变?
- 为什么提升图库的 read_graphviz() 函数会改变节点的索引
- 何时为派生类初始化 vptr?
- 如何知道何时调用删除以及何时调用 delete[] C++?
- Windows错误报告何时创建转储文件?它是否可配置?这在Windows 7中有改变吗?
- 这个char *为什么以及何时改变值