c++ - 如何在默认构造函数中初始化对空字符串的类成员引用

标签 c++ reference default-constructor

如何在此默认构造函数中初始化对空字符串 ("") 的类成员引用。

class Document {
    string& title;
    string* summary;

    Document() : title(/*what to put here*/), summary(NULL) {}
};

最佳答案

没有明智的方法可以做到这一点。引用必须引用现有对象(更好的说法是引用 现有对象),而 std::string 将是从 "" 构造的初始化列表将在构造函数完成后被销毁,每次尝试使用您的成员变量时都会留下未定义的行为。

现在,我说“没有明智的方法”。当然,有一些黑客可以实现你想要的,例如:

// bad hack:
std::string &EmptyStringThatLivesForever()
{
    static std::string string;
    return string;
}

class Document {
    string& title;
    string* summary;

    Document() : title(EmptyStringThatLivesForever()), summary(NULL) {}
};

但我怀疑这样的技巧能否经受住任何严格的代码审查。

真正的解决办法是去掉引用:

class Document {
    string title;
    string* summary;

    Document() : title(""), summary(NULL) {}
};

关于c++ - 如何在默认构造函数中初始化对空字符串的类成员引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28659278/

相关文章:

dictionary - 在参数中使用的 slice vs map

c++ - 类不存在默认构造函数,但我已经声明了一个

c++ - 涉及函数绑定(bind)的代码含义

c++ - 如何强制不修改引用变量的任何部分?

Python 函数通过引用调用

c++ - 如何使用自定义删除器创建 unique_ptr 数组?

C++ 默认构造函数

c++ - 帮我调试这个 - C++ Boost

c++ - 当我们不知道类型的大小时如何为类型分配内存?

c++ - 无法使派生的WebDuino类正常工作-使用 'Web_HelloWorld.ino'编译错误