Domanda

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.

È stato utile?

Soluzione

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.

Altri suggerimenti

That's becouse the operator assignement of auto_ptr takes's the ownership (move) the pointer

Take a read on Wiki, it's quite good general explanation:

http://en.wikipedia.org/wiki/Smart_pointer

"The copy constructor and assignment operators of std::auto_ptr do not actually copy the stored pointer. Instead, they transfer it, leaving the previous std::auto_ptr object empty. This was one way to implement strict ownership, so that only one auto_ptr object could own the pointer at any given time. This means that auto_ptr should not be used where copy semantics are needed."

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top