tags:

views:

94

answers:

2

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.

+3  A: 

Things wrong with it:

  • A is never deleted.
  • f isn't declared.
  • B should probably be of type auto_ptr<tClass>.
  • new tClass() is of type tClass* which isn't the right type to assign to B.
ChrisW
+6  A: 

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.

TokenMacGuy
May be you want to mention that `auto_ptr` is deprecated in favor of `unique_ptr`: http://stackoverflow.com/questions/2404115/is-auto-ptr-deprecated. Also, is the pair of parentheses after `tClass` really required?
ArunSaha
@ArunSaha: it's not deprecated *yet*. C++0x isn't yet standard :)
jalf
"When you pass an auto_ptr to a function..." only true for by-value passage; f() might accept a reference to the auto_ptr.
Tony
@Tony: hadn't thought of that. good point. scary.
TokenMacGuy