Difference between pointer and smart pointer
Can you tell me what is wrong with this piece of code? I got asked this in an inte开发者_如何学JAVArview 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.
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.
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 typetClass*
which isn't the right type to assign to B.
精彩评论