相关疑难解决方法(0)

临时的一生

以下代码工作正常,但为什么这是正确的代码?为什么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)

c++ temporary c++-faq lifetime full-expression

37
推荐指数
2
解决办法
3149
查看次数

延长临时生命周期,使用块作用域聚合,但不能通过`new`; 为什么?

注意:这个问题本来是问,评论 瑞安海宁这个答案.


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)


  • 为什么临时的生命期延长到(1),而不是(2)

c++ object-lifetime language-lawyer c++11

10
推荐指数
1
解决办法
181
查看次数

将 const 引用成员设置为临时变量是否安全?

我试过多次这样编码:

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来测试程序,但没有出现错误或警告。所以,我假设编译器自动生成了一个代码,将引用指向另一个隐藏变量。但我真的不确定。

c++ reference constants temporary lifetime

6
推荐指数
1
解决办法
2852
查看次数

警告:在此函数中使用未初始化的“&lt;anonymous&gt;”[-Wuninitialized]

以下程序编译时不会出现警告-O0

\n\n
#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}\n
Run Code Online (Sandbox Code Playgroud)\n\n

但是,使用-O1或更高版本会发出警告:

\n\n
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;\n
Run Code Online (Sandbox Code Playgroud)\n\n

如何摆脱这个警告-O1

\n\n

这样做的动机是CHECK(x)宏必须捕获 const 引用而不是值,以免触发析构函数、复制构造函数等以及打印出值。 …

c++

6
推荐指数
1
解决办法
4670
查看次数