foo
아래 참조 변수 는의 인스턴스 Foo
또는에 Bar
기반한 파생 클래스 로 초기화 됩니다 condition
. 이상하게도 say()
메소드 의 출력을 기반으로 foo
할 때 인스턴스가 Foo
아닌 인스턴스 인 것 같습니다. Bar
왜?
#include <iostream>
class Foo {
public:
virtual void say() const {
std::cout << "Foo\n";
}
};
class Bar : public Foo {
public:
virtual void say() const {
std::cout << "Bar\n";
}
};
int main() {
constexpr bool condition = false;
const Foo& foo = condition ? Foo() : Bar();
foo.say(); // outputs "Foo” ???
return 0;
}
각 생성자에 주석을 달면 Bar
삼항 표현식을 평가할 때 생성자가 호출되는 것을 볼 수 있습니다 . 각 소멸자에 주석을 달면 소멸자 가 초기화 되기 전에Bar
호출 된다는 것을 알 수 있습니다. 이것은 임시 객체가 삼항 연산자에 의해 생성되었지만 초기화 전에 파괴 되었음을 나타냅니다. 이유는 무엇입니까? foo
Bar
(Apple LLVM 버전 9.0.0 (clang-900.0.39.2))로 컴파일 됨
clang++ -Wall -std=c++11 foo.cpp -o foo
문제
const Foo& foo = condition ? Foo() : Bar();
두 부분 모두 동일한 유형을 반환해야한다는 것입니다. 이후 Foo()
와 Bar()
동일한 유형 없습니다, 컴파일러는 변환하려고합니다. 그것이 할 수있는 유일한 유효한 변환은 Bar()
그 Foo
부분 으로 분할 하는 것 입니다. 이것은 당신이 무엇을 얻든간에 참조를 a에 바인딩 Foo
하고 Bar
부품이 사라짐을 의미합니다.
이 문제를 해결하려면 다음과 같은 포인터를 사용해야합니다.
#include <iostream>
#include <memory>
class Foo {
public:
virtual ~Foo() = default; // don't forget to add this when using polymorphism
virtual void say() const {
std::cout << "Foo\n";
}
};
class Bar : public Foo {
public:
virtual void say() const {
std::cout << "Bar\n";
}
};
int main() {
constexpr bool condition = false;
auto foo = condition ? std::make_unique<Foo>() : std::make_unique<Bar>();
foo->say(); // outputs "Bar" now
return 0;
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다