我检查了gcc和clang,两者都没有生成任何警告.我想从foo()临时的生命周期将延长,直到完整表达式结束,这是bar函数调用中的分号所在.
#include <iostream>
#include <string>
struct A
{
std::string foo() const{ return "aaa"; }
};
void bar(const char* c) {
std::cout << c;
}
int main()
{
A a;
bar(a.foo().c_str()); // Is this safe?
bar(a.foo().substr().c_str()); // or this
}
Run Code Online (Sandbox Code Playgroud)
foo()(和substr())返回的临时值将继续存在,直到bar调用结束(方法调用链之后),这是安全的.
int main()
{
A a;
bar(a.foo().c_str());
//temporary is destroyed here
bar(a.foo().substr().c_str());
// and here
}
Run Code Online (Sandbox Code Playgroud)
经典的未定义行为案例:
int main()
{
A a;
const char* charPtr = a.foo().c_str();
printf("%s", charPtr);
}
Run Code Online (Sandbox Code Playgroud)
std::string创建临时,返回指向它的缓冲区的指针,c_str()临时超出范围并被销毁.charPtr现在是一个指向无效位置(死机std::string)的指针.
| 归档时间: |
|
| 查看次数: |
199 次 |
| 最近记录: |