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?
source
share