c++ - c++构造函数的奇怪行为

标签 c++ c++11

我正在测试这段代码,想知道为什么它在编译时没有失败?。我正在使用 c++11 和 g++ 4.7.2。

我的生产代码有类似的结构,它在运行时出错,然后我发现我正在用错误的参数类型构造类。

#include <iostream>
#include <vector>


typedef std::vector<std::string> Word;

class Data {
    public:
        const Word &word;
        Data(Word w) : word(w) {}
};

class Base{
    const Data &data;
    public:
        Base(const Data &d): data(d) {}
        ~Base() {}
};

class Work : public Base{
    public:
        Work(const Data &d): Base(d){}
        ~Work() {}
};


int main(int argc, char **argv){
    Word words;
    words.push_back("work");

    /*
    * I'm confused with this constructor, why this passed the compilation
    * ??
    * Any special rule to reason this scenario ??
    *
    * But obviously it will fail at run time.
    */
    const Work *work  = new Work(words);

    return 0;
}

最佳答案

Data 可从 Word 构造,因此您可以将 Word 传递给 Work 构造函数。在引擎盖下,Data 的实例将从传递的 Word 创建,然后传递给构造函数。

您可以通过将采用WordData 构造函数标记为explicit 来避免这种情况。 ,像这样:

class Data {
    public:
        const Word &word;
        explicit Data(Word w) : word(w) {}
};

那样的话,构造函数就不能再隐式应用了,除非显式调用 Data 构造函数,否则对 Work 构造函数的调用将无法编译:

const Work *work  = new Work(words);        // Implicit call, fails to compile.
const Work *work  = new Work(Data(words));  // Explicit call, compiles.

关于c++ - c++构造函数的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18652524/

相关文章:

c++ - PCL 用指针替换点云?

c++ - 有人可以帮我解决这个错误吗?

c++ - boost POOL 使用率 - 单例

c++ - 谷歌日志记录中的自定义日志级别

c++ - 将 for_each 与 std::unique_ptr 一起使用

c++ - 如何从此指针获取 std::weak_ptr<MyClass> ?

c++ - 如何让我的程序监视 C++ 中的文件修改?

C++ - 智能指针 vector 图 - 全部继承自同一基类

c++ - std::array 位是否与旧的 C 数组兼容?

c++ - 由 Visual Studio 2013 Update 2 和 Update 3 生成的 SSE 4 指令