以下代码工作正常,但为什么这是正确的代码?为什么foo()返回的临时的"c_str()"指针有效?我想,当输入bar()时,这个临时性已经被破坏了 - 但它似乎不是这样的.那么,现在我假设foo()返回的临时值将在调用bar()之后被销毁 - 这是正确的吗?为什么?
std::string foo() {
std::string out = something...;
return out;
}
void bar( const char* ccp ) {
// do something with the string..
}
bar( foo().c_str() );
Run Code Online (Sandbox Code Playgroud) struct A { std::string const& ref; };
Run Code Online (Sandbox Code Playgroud)
// (1)
A a { "hello world" }; // temporary's lifetime is extended to that of `a`
std::cout << a.ref << std::endl; // safe
Run Code Online (Sandbox Code Playgroud)
// (2)
A * ptr = new A { "hello world" }; // lifetime of temporary not extended?
std::cout << ptr->ref << std::endl; // UB: dangling reference
Run Code Online (Sandbox Code Playgroud)
题
我试过多次这样编码:
struct Foo
{
double const& f;
Foo(double const& fx) : f(fx)
{
printf("%f %f\n", fx, this->f); // 125 125
}
double GetF() const
{
return f;
}
};
int main()
{
Foo p(123.0 + 2.0);
printf("%f\n", p.GetF()); // 0
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但它根本不会崩溃。我还使用valgrind来测试程序,但没有出现错误或警告。所以,我假设编译器自动生成了一个代码,将引用指向另一个隐藏变量。但我真的不确定。
以下程序编译时不会出现警告-O0:
#include <iostream>\n\nstruct Foo\n{\n int const& x_;\n inline operator bool() const { return true; }\n Foo(int const& x):x_{x} { }\n Foo(Foo const&) = delete;\n Foo& operator=(Foo const&) = delete;\n};\n\nint main()\n{\n if (Foo const& foo = Foo(3))\n std::cout << foo.x_ << std::endl;\n\n return 0;\n}\nRun Code Online (Sandbox Code Playgroud)\n\n但是,使用-O1或更高版本会发出警告:
maybe-uninitialized.cpp: In function \xe2\x80\x98int main()\xe2\x80\x99:\nmaybe-uninitialized.cpp:15:22: warning: \xe2\x80\x98<anonymous>\xe2\x80\x99 is used uninitialized in this function [-Wuninitialized]\n std::cout << foo.x_ << std::endl;\nRun Code Online (Sandbox Code Playgroud)\n\n如何摆脱这个警告-O1?
这样做的动机是CHECK(x)宏必须捕获 const 引用而不是值,以免触发析构函数、复制构造函数等以及打印出值。 …