Search code examples
c++pointersauto-ptr

Auto Pointer in C++ (auto_ptr)


I am trying to figure out what this piece of code prints but I couldn't output it for some reason, it gave me an error: "1 [main] Q1c 5752 open_stackdumpfile: Dumping stack trace to Q1c.exe.stackdump".

double *dp=new double(1.2);
auto_ptr <double> autodp1(dp);
auto_ptr <double> autodp2=autodp1;
cout<<*autodp1<<endl;

I just want to know what it will print, if it even prints.

Notice: this question was in past exam paper, just for revision.


Solution

  • The code *autodp1 is effectively a dereferencing of a null pointer. Therefore the code exhibits undefined behavior.

    You first construct autodp1 to point to the newly allocated double. But then the constructor of autodp2 takes the owned memory for itself and sets autodp1 to null.