shared_ptr from unique_ptr to an array

后端 未结 1 1463
萌比男神i
萌比男神i 2020-12-21 12:08

Scott Meyers mentions in his book, Effective Modern C++, that using shared_ptr to arrays is discouraged because when converted to Base class pointers i

1条回答
  •  梦毁少年i
    2020-12-21 12:37

    Is the above code potentially dangerous?

    It depends what you do with it.

    It won't leak resources because the default_delete that uses delete[] will be copied from the unique_ptr and stored in the shared_ptr (as described at Initialization of shared_ptr from unique_ptr).

    Are there pitfalls if pDerived is later copied into a pBase?

    Yes, if you do something like pBase.get()[1] then that is not a valid pointer to the second element if sizeof(B) != sizeof(D)

    std::experimental::shared_ptr from the Library Fundamentals TS supports arrays properly (as proposed by N3939).

    With the version in the TS, shared_ptr does not allow construction from a unique_ptr, but shared_ptr does. A shared_ptr cannot be converted to shared_ptr, to avoid the safety problem you refer to.

    The support for arrays might make it into std::shared_ptr in a future C++ standard, but is only in the TS for now.

    0 讨论(0)
提交回复
热议问题