我正在测试此代码,想知道为什么在编译时没有失败?我正在使用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
实例,然后将其传递给构造函数。
您可以通过将采用Data
的Word
构造函数标记为explicit来避免这种情况,如下所示:
class Data {
public:
const Word &word;
explicit Data(Word w) : word(w) {}
};
这样,就不能再隐式应用该构造函数了,除非您显式调用
Work
构造函数,否则对Data
构造函数的调用将无法编译: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/