code

std :: shared_ptr을 다운 캐스트하는 방법은 무엇입니까?

codestyles 2020. 12. 7. 08:10
반응형

std :: shared_ptr을 다운 캐스트하는 방법은 무엇입니까?


중히 여기다:

struct SomethingThatsABase
{
    virtual bool IsChildOne() const { return false; }
    virtual bool IsChildTwo() const { return false; }
};

struct ChildOne : public SomethingThatsABase
{
    virtual bool IsChildOne() const { return true; }
};

struct ChildTwo : public SomethingThatsABase
{
    virtual bool IsChildTwo() const { return true; }
};

void SomeClientExpectingAChildOne(std::shared_ptr<ChildOne> const& ptrOne)
{
    //Does stuff
}

void SomeClient(std::shared_ptr<SomethingThatsABase> const& ptr)
{
    if (ptr->IsChildOne())
    {
        SomeClientExpectingAChildOne(ptr); //Oops.
        //Hmm.. can't static_cast here, because we need a `shared_ptr` out of it.
    }
}

( std::shared_ptr<ChildOne>(static_cast<ChildOne*>(ptr.get()))참조 카운트가 두 shared_ptrs 간에 공유되지 않기 때문에 간단히 할 수는 없습니다. )


이것은 작동해야합니다.

if (ptr->IsChildOne())
{
    SomeClientExpectingAChildOne(std::static_pointer_cast<ChildOne>(ptr));
}

shared_ptr해당하는 static_cast것은 static_pointer_cast이고에 shared_ptr해당하는 dynamic_cast것은 dynamic_pointer_cast입니다.


C ++ 11부터 C ++ 표준의 §20.10.2.2.9 ( [util.smartptr.shared.cast] )는 static_cast, const_castdynamic_castfor std::shared_ptr에 해당하는 항목을 다음과 같이 지정합니다.

std::static_pointer_cast:

template <class T, class U>
shared_ptr<T> static_pointer_cast(shared_ptr<U> const & r) noexcept;

static_pointer_cast요구가 static_cast<T *>(r.get())잘 형성된다. 경우 r빈, 비어 shared_ptr<T>그렇지 않으면 포인터 반환, 반환 w과 함께 공유 소유권 rw.get() == static_cast<T *>(r.get())w.use_count() == r.use_count().

std::const_pointer_cast:

template <class T, class U>
shared_ptr<T> const_pointer_cast(shared_ptr<U> const & r) noexcept;

const_pointer_cast has similar requirements and semantics to static_pointer_cast, except that const_cast is used instead of static_cast.

std::dynamic_pointer_cast:

template <class T, class U>
shared_ptr<T> dynamic_pointer_cast(shared_ptr<U> const & r) noexcept;

dynamic_pointer_cast is a bit different as it requires dynamic_cast<T *>(r.get()) to be well formed and have well defined semantics. If dynamic_cast<T *>(r.get()) is a non-zero value, returns a pointer w sharing ownership with r where w.get() == dynamic_cast<T *>(r.get()) and w.use_count() == r.use_count(), otherwise an empty shared_ptr<T> is returned.

std::reinterpret_pointer_cast:

For C++17, N3920 (adopted into Library Fundamentals TS in February 2014) also proposed a std::reinterpret_pointer_cast similar to the above, which would only require reinterpret_cast<T *>((U *) 0) to be well formed and returns shared_ptr<T>(r, reinterpret_cast<typename shared_ptr<T>::element_type *>(r.get())). Note N3920 also changed the wording for the other shared_ptr casts and extended shared_ptr to support arrays.

참고URL : https://stackoverflow.com/questions/6795629/how-does-one-downcast-a-stdshared-ptr

반응형