What happens if I reset a std :: shared_ptr for myself

The following program crashes with a bad double glibc error:

#include <iostream>
#include <memory>

class foo {
public:
   foo()
   {
      std::cout << "foo constructed" << std::endl;
   }

   ~foo()
   {
      std::cout << "foo destructed" << std::endl;
   }
};

int main() {
   auto f = std::make_shared< foo >();
   std::cout << "Before reset" << std::endl;
   f.reset( f.get() );
   std::cout << "After reset" << std::endl;
   return 0;
}

From this, I get the following output (followed by a glibc error):

foo constructed
Before reset
foo destructed
After reset
foo destructed

Thus, it is obvious that in this case the object is destroyed twice. Once reset and once std::shared_ptrout of scope. This is what I expected.

In cppreference however, I found the following text (found at http://en.cppreference.com/w/cpp/memory/shared_ptr/reset ):

If * this already belongs to the object, and it is the last shared_ptr that owns it, the object is destroyed through its debit, unless ptr is a pointer to it.

-, , , . , . - , std::shared_ptr ?

, , :

, , new new[]. , std::shared_ptr::reset() . try { stuff() } catch( ... ) { delete x; throw;}.

+5
1

reset 20.7.2.2.4 shared_ptr [util.smartptr.shared.mod], 3 ( n3290):

template<class Y> void reset(Y* p);

: shared_ptr(p).swap(*this).

, shared_ptr(p) deleter p, . std::shared_ptr<T>::get , - , - .

, std::unique_ptr<T> release, , , . , , std::unique_ptr<T>? std::shared_ptr<T>, , . (, std::shared_ptr<T> deleter std::unique_ptr<T>, , , , std::shared_ptr<T*> std::unique_ptr<T[]>.)

+7

All Articles