我有以下代码,使用 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;
}
但是当我运行它时,只打印出换行符。到底是怎么回事?
如果我要在里面做这个事情:
string temp("snoop");
Foo f(temp);
f.print();
然后就可以正常工作了!
失败的原因是它本质上在底层编译为以下内容。
Foo o(std::string("wurd"));
在这种情况下Foo
value 引用一个临时对象,该对象在构造函数完成后被删除。因此它保持着死值。第二个版本之所以有效,是因为它保存了对本地的引用,该引用的生命周期比Foo
实例。
为了解决这个问题,将成员从const std::string&
to a const std::string
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)