相关疑难解决方法(0)

const引用类成员是否延长了临时生命?

为什么这样:

#include <string>
#include <iostream>
using namespace std;

class Sandbox
{
public:
    Sandbox(const string& n) : member(n) {}
    const string& member;
};

int main()
{
    Sandbox sandbox(string("four"));
    cout << "The answer is: " << sandbox.member << endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

给出输出:

答案是:

代替:

答案是:四

c++ temporary const-reference ctor-initializer

157
推荐指数
3
解决办法
4万
查看次数

临时的一生

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