c ++传递字符串文字而不是const std :: string&?

Vic*_*mar 7 c++ string reference literals

我有以下代码,使用g ++编译没有警告(-Wall -pedantic)

#include <iostream>
#include <string>

using namespace std;

class Foo
{
public:
    Foo(const std::string& s) : str(s)
    { }

    void print()
    {
        cout << str << endl;
    }

private:
    const std::string& str;
};


class Bar
{
public:

    void stuff()
    {
        Foo o("werd");
        o.print();
    }
};


int main(int argc, char **argv)
{
    Bar b;
    b.stuff();

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

但是当我运行它时,只打印出换行符.到底是怎么回事?

如果我要在里面做这件事:

string temp("snoop");
Foo f(temp);
f.print();
Run Code Online (Sandbox Code Playgroud)

然后它工作正常!

Jar*_*Par 21

这种失败的原因是因为它基本上编译成了以下内容.

Foo o(std::string("wurd"));
Run Code Online (Sandbox Code Playgroud)

在这种情况下,该Foo值将引用一个临时对象,该对象在构造函数完成后被删除.因此它保持了死亡价值.第二个版本有效,因为它持有对具有比Foo实例更长寿命的本地的引用.

为了解决这个问题,将memebr从a const std::string&改为a const std::string.

  • @MilesRout 这不完全正确。您可能知道您不想修改字符串,并通过将其声明为 const 来允许编译器验证您不想修改。 (3认同)