Lol*_*ums -2 c++ string stringstream
我不知道这里出了什么问题。
std::stringstream ss("Title");
ss << " (" << 100 << ")";
const char* window_title = &ss.str().c_str();
Run Code Online (Sandbox Code Playgroud)
我跑了make,它不开心。
[17%] Building CXX object CMakeFiles/game.dir/src/main.cpp.o
path: error: cannot take the address of an rvalue of type 'const value_type *'
(aka 'const char *')
const char* window_title = &ss.str().c_str();
^~~~~~~~~~~~~~~~~
1 error generated.
make[2]: *** [CMakeFiles/game.dir/src/main.cpp.o] Error 1
make[1]: *** [CMakeFiles/game.dir/all] Error 2
make: *** [all] Error 2
Run Code Online (Sandbox Code Playgroud)
据我所知,我正在创建一个stringstream带有“标题”一词的内容,然后在其后附加“(100)”。在此之后,我正在检索一个字符串,然后是一个“C 字符串”,它是 achar并将指向该字符串的指针存储在window_title.
怎么了?
ss.str()返回一个在调用后销毁的临时对象。您不应该使用指向临时对象内存的指针,这是未定义的行为。此外,c_str()已经返回一个指向以空字符结尾的字符数组的指针。编译器抱怨您试图不只是使用临时对象的内存地址,而是获取指向该地址的指针,这是理所当然的。这样它编译和工作
std::stringstream ss("Title");
ss << " (" << 100 << ")";
//Create a string object to avoid using temporary object
std::string str = ss.str();
const char* window_title = str.c_str();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
842 次 |
| 最近记录: |