2016-10-13 5 views
3

cpp referenceshared_from_this 및 개인 상속

class Good : std::enable_shared_from_this<Good> 
{ 
    public: std::shared_ptr<Good> getptr() { return shared_from_this(); } 
}; 

... 

auto good = std::make_shared<Good>(); 
good->getptr(); 

그러나이 Visual Studio에서 작동하지 않는다 (약간 조정) std::enable_shared_from_this를 사용하는 방법이 예제를 가지고 2015 년 (엔터프라이즈 버전 14.0.25123.00 업데이트 2), 즉, std::bad_weak_ptr 예외가 발생합니다.

은 (cpp reference 또는 Microsoft 다른 사람을 포함한) 다른 예를 보면 나는 그들이 대신 private 하나의 public 상속을 사용하는 것으로 나타났습니다. 그리고 public 상속을 사용하면 실제로 내 문제가 해결됩니다 (아니 std::bad_weak_ptr 더 이상 유효하지만 대신 shared_ptr).

Cpp 참조는 공개적으로 std::enable_shared_from_this에서 상속해야한다는 언급이 없으므로 어디에 오류가 있습니까? Visual Studio의 동작이 잘못 되었습니까 (private 상속을 사용할 때 가시성 문제가있는 것 같습니까?) 또는이 제한을 언급하지 못한 cpp 참조가 있습니까?

PS : make_shared<good>() 또는 shared_ptr<Good>(new Good)은 차이가 없습니다.

PSS : 두 버전 모두 제대로 컴파일되지만 사적인 버전은 제대로 작동하지 않으므로 매우 불쾌한 버그가 발생합니다.

편집 : struct에서 class으로 변경. Cpp 참조는 실제로 해당 예제에서 공용 상속을 사용합니다. 아직 공개되어야한다는 말은 없습니다. 실제로 목록에 나와 있습니다. 단지 신중하게 읽는 법을 배워야합니다. @Angew 감사합니다.

+0

가능한 복제 (HTTP : // 유래 .com/questions/27697973/shared-from-this-causing-bad-weak-ptr) –

+0

@ πάνταῥε other 다른 질문에 다른 근본 원인이있다. –

+0

@PiotrSkotnicki 나는 그것을 망치지 않았다. –

답변

2

std::enable_shared_from_this의 전형적인 구현은, (귀하의 경우 std::make_shared에 의해라고도 함) std::shared_ptr 생성자가 그베이스의 std::weak_ptr 멤버를 설정할 수 있도록하는 std::enable_shared_from_this 기지의 존재를 감지 할 수 있도록해야합니다. 개인 상속

, 그건 불가능하므로합니다 (std::weak_ptr가 설정되지 않았기 때문에 std::shared_ptr 생성자가 std::enable_shared_from_this 기반을 감지 할 수 있기 때문에,) shared_from_this를 호출 할 때 당신이있어 런타임 예외를 얻을.

은 C++ 표준 언급 그러한 구현 : 가능한 구현은 다음과 같다 :

[참고의 존재를 감지 할 수있는 고유 포인터를 생성

template<class T> class enable_shared_from_this { 
private: 
    weak_ptr<T> __weak_this; 
protected: 
    constexpr enable_shared_from_this() : __weak_this() { } 
    enable_shared_from_this(enable_shared_from_this const &) { } 
    enable_shared_from_this& operator=(enable_shared_from_this const &) { return *this; } 
    ~enable_shared_from_this() { } 
public: 
    shared_ptr<T> shared_from_this() { return shared_ptr<T>(__weak_this); } 
    shared_ptr<T const> shared_from_this() const { return shared_ptr<T const>(__weak_this); } 
}; 

shared_ptr 생성자 enable_shared_from_this을 새로 만들고 새로 만든 shared_ptr__weak_this 구성원에 할당합니다. - 엔드 노트]

cppreference page 당신은에 또한 노트이 언급 연결됩니다.

+0

설명해 주셔서 감사합니다. 나는 이것이 여전히 미묘한 오류의 원인이라고 생각하지만, 어떤 종류의 정적 인 어설 션으로도 발견 될 수 없다고 생각한다. –

+0

@ArtificialMind : 그들은'std :: enable_shared_from_this' 구현에 다음과 같은 것을 추가 할 수 있습니다 : static_assert (std :: is_convertible :: value, "Public 상속이 필요합니다.") 위에서 언급 한 구현) –

1

질문의 코드는 모든 개인 상속을 사용하지 않습니다 : 회원 및 기본 클래스에 대한 공공 액세스 제어에 struct 기본값.

또한 cppreference은 아무 것도 생략하지 않습니다. 페이지의 텍스트는 명확하게 상태 : 공개적으로 std::enable_shared_from_this<T>에서 상속

... [bad_weak_ptr 원인 ​​shared_from_this]의

(강조 광산)

+0

주의 해 주셔서 감사합니다! 내 프로덕션 코드는 클래스를 사용하므로 여전히 실패했습니다. 적어도 cpp 참조는 일관성이 있습니다. –

관련 문제