const ref初始化非常奇怪的输出

Kro*_*ark 1 c++ gcc

在我的一个项目中,我初始化了一个const std :: string&with const char(在编译时知道),打印结果是......令人惊讶.

我在Ubuntu 12.04x32上使用gcc版本4.6.3(Ubuntu/Linaro 4.6.3-1ubuntu5)

例:

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

class A
{
    public:
        A() : str("test"){};
    const string& str;
};

int main(int argc,char* argv[])
{ 
  A a;
  cout<<a.str<<endl;
  return 0;
};
Run Code Online (Sandbox Code Playgroud)

所以,正常情况下,它会显示"测试"但是,这是我输出的prt:

testP?????utf8)????lower_case_table_names?xW?xW? ??     ????127.0.0.1utf8W?Y127.0.0.1 via TCP/IP127.0.0.1
        ?5.5.31-0ubuntu0.12.04.1rootW?rootW?1????metadata_use_info_schema!P?XP?? VARa?pW?P4:????SHOW SESSION VARIABLES LIKE 'lower_case_table_names'`(???TCP/IP (3)@!K!K!?
.....
<charset name="gb2312">
  <family>Simplified Chinese</family>
  <description>GB2312 Simplified Chinese</description>
  <alias>chinese</alias>
  <alias>iso-ir-58</alias>
   <collation name="gb2312_chinese_ci"  id="24" order="Chinese">
    <flag>primary</flag>
   <flag>compiled</flag>
  </collation>
  <collation name="gb2312_bin"  id="86">
    <flag>binary</flag>
    <flag>compiled</flag>
  </collation>
</charset>
Run Code Online (Sandbox Code Playgroud)

输出连续1000行.

所以我的问题很简单:为什么?(我尝试在"测试"结束时添加\ 0,但没有更改)

And*_*owl 11

这是因为您正在取消引用悬空引用,这会为您的程序提供未定义的行为.根据C++ 11标准的第12.2/5段:

[...]绑定到构造函数的ctor-initializer(12.6.2)中的引用成员的临时绑定将持续存在,直到构造函数退出.[...]

这意味着构造函数初始化列表中绑定的临时std::string对象str在您解除反复时将会死亡str.

你有两种方法.要么使您的数据成员str成为a const char*,要么使其成为std::string(不是引用类型).我个人会选择最后一个选项:

class A
{
public:
    A() : str("test") { }
    std::string str;
};
Run Code Online (Sandbox Code Playgroud)

另请注意,在函数定义之后不需要分号.