AutoPointer with objects not allocated to the heap

An automatic pointer internally causes the object that it points to to be deleted when it goes out of scope. This works great if we assign an object created on the heap. But if I try to assign an object that is not created on the heap, it will work, since delete is called twice. First, auto_ptr first, and second, since the object is out of scope, its destructor is called again. As below

#include <iostream>
#include <memory>

using namespace std;

class sample
{
      public:
             sample() { puts("sample"); }
             ~sample() { puts("~sample"); }
};

int main()
{
    sample sObj;
    auto_ptr<sample> samplePtr(&sObj);
}

Does this mean that we can use auto_ptr to store only objects created on the heap?

+3
source share
5 answers

, , auto_ptr . - auto_ptr delete, delete , , - undefined, , , - , .

+3

- .

, auto_ptr. , , , .

+2

(, " " ) . auto_ptr , new ( delete ). auto_ptr , new.

+2

std:: auto_ptr, , .

, , boost:: shared_ptr, , , . , , , .
. boost:: shared_ptr

std:: auto_ptr - ++ 11,
. ++ 11 std:: auto_ptr

+2

, auto_ptr , ?
.
, , - , .

Note that you can use shared_ptror unique_ptr, which gives you the ability to call a custom delete function. You can use specialized memory allocators instead newwith this custom delete function.

auto_ptris deprecated and the C ++ standard offers a unique_ptrbetter alternative.

+1
source

All Articles