이 코드를 테스트하고 있는데 이것이 컴파일 타임에 실패하지 않은 이유가 궁금하십니까? 저는 C++ 11과 g ++ 4.7.2를 사용하고 있습니다.C++ 생성자의 이상한 동작
필자의 프로덕션 코드에서 비슷한 구조를 가졌으므로 런타임에 오류가 발생했다가 잘못된 인수 유형으로 클래스를 생성하고있는 것으로 나타났습니다. 당신이 Work
생성자에 Word
를 통과 할 수 있도록
#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 생성자에 의해 Data로 변환 된 다음 Work (Data)를 호출합니다. – ZijingWu
왜 실패해야합니까? http://ideone.com/cxkf4X에서 성공을 반환합니다. – xanatos