Search code examples
c++c++11shared-ptr

C++11's shared_ptr assignment


I have the following code:

    #include <memory>

    int main(void)
    {
        std::shared_ptr<int> currInt(nullptr);

        std::shared_ptr<int> newInt(new int);
        currInt = newInt;

        return 0;
    }

It turns out that this isn't valid C++11 (it use to be in the draft versions) and that the assignment constructor now uses move semantics. Something I don't understand.

Could somebody please explain how I'd modify the code above to make it.. work?


Solution

  • There is a copy constructor for shared_ptr, otherwise what's the point of a shared_ptr?

    The clang link by OP is saying that if only the move assignment operator is defined, then the copying constructor will be implicitly deleted, making the shared_ptr not behaving correctly. This can be seen in the Boost changeset as well, where the copy assignment operators are explicitly added to correct the bug.

    You can find the copy assignment operators of shared_ptr in §20.7.2.2.3[util.smartptr.shared.assign]/1­–3.

    shared_ptr& operator=(const shared_ptr& r) noexcept;
    template<class Y> shared_ptr& operator=(const shared_ptr<Y>& r) noexcept;
    template<class Y> shared_ptr& operator=(auto_ptr<Y>&& r);