Reputation: 2435
Can you tell me what is wrong with this piece of code? I got asked this in an interview and I am not sure what's wrong with it
tClass is a test class with a method printSomething that prints members of tClass.
tClass * A = new tClass();
f(A);
A->printSomething();
auto_ptr<tClass> * B = new tClass();
f(B);
B-> printSomething();
or what this is a trick question.
Upvotes: 1
Views: 1369
Reputation: 156228
auto_ptr is a type of smart pointer that operates under the premise that exactly one party owns the pointer, and if that owning party goes out of scope, the pointer gets deleted.
When you pass an auto_ptr to a function, you are "Giving" the function that pointer, and so you don't have it anymore. when you dereference it, you get a null pointer behavior (which is undefined, of course).
In order to get your code to compile, though, you have to change your definition of B
a bit, it should be
auto_ptr<tClass> B = new tClass;
since auto_ptr is not a type (its a type template), and you don't actually want a pointer to that type at all, since the class overloads those behaviors.
Upvotes: 6
Reputation: 56113
Things wrong with it:
auto_ptr<tClass>
.new tClass()
is of type tClass*
which isn't the right type to assign to B.Upvotes: 3