c ++传递字符串文字而不是const std :: string& ;? [英] c++ passing a string literal instead of a const std::string&?
问题描述
我有以下代码,使用g ++编译时不会发出警告(-Wall -pedantic)
I have the following code which compiles with no warnings (-Wall -pedantic) with g++
#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;
}
但是当我运行它时,只打印换行符. 发生了什么事?
But when I run it, only the newline is printed out. What is going on?
如果我要在内部做这些事情:
If I were to do this inside stuff:
string temp("snoop");
Foo f(temp);
f.print();
然后一切正常!
推荐答案
之所以失败,是因为它本质上可以编译为以下内容.
The reason why this fails is because it essentially compiles to the following under the hood.
Foo o(std::string("wurd"));
在这种情况下,Foo
值引用了一个临时对象,该临时对象在构造函数完成后将被删除.因此,它一直保持着无效值.第二个版本起作用是因为它持有对本地的引用,该本地的生存期比Foo
实例的生存期更长.
In this case the Foo
value is taking a reference to a temporary object which is deleted after the constructor completes. Hence it's holding onto a dead value. The second version works because it's holding a reference to a local which has a greater lifetime than the Foo
instance.
要解决此问题,请将memebr从const std::string&
更改为const std::string
.
To fix this change the memebr from being a const std::string&
to a const std::string
.
这篇关于c ++传递字符串文字而不是const std :: string& ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!