c ++传递字符串文字而不是const std :: string&amp ;? [英] c++ passing a string literal instead of a const std::string&?

查看:135
本文介绍了c ++传递字符串文字而不是const std :: string&amp ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,使用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&amp ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆