If I have a auto_ptr I can pass it for a reference?Like:
auto_ptr<MyClass>Class(new MyClass);
void SetOponent(MyClass& oponent);
//So I pass SetOponent(Class)
And what is odd copy behavior of auto_ptrs?
If I have a auto_ptr I can pass it for a reference?Like:
auto_ptr<MyClass>Class(new MyClass);
void SetOponent(MyClass& oponent);
//So I pass SetOponent(Class)
And what is odd copy behavior of auto_ptrs?
No you can't, you would have to dereference it:
SetOponent( * Class )
As for the copying behaviour, I recommend you read a good book on C++, such as Effective C++ by Scott Meyers. The copying behaviour of auto_ptr is extremely un-intuitive and possibly beyond the scope of an SO answer. However, nothing ventured...
When an auto_ptr is copied, ownership is transferred from the original to the copy. For example:
auto_ptr <Foo> p1( new Foo );
at this point p1 owns the pointer to the Foo object.
auto_ptr <Foo> p2( p1 );
After the copy, p2 owns the pointer and p1 is changed so that it now holds a NULL pointer. This is important, because copying occurs in lots of places in C++. You should never, for example, pass auto_ptrs by value to functions, or attempt to store them in standard library containers.
The odd copy behavior is that you can't make a copy and still have the original. Use shared_ptr
(in boost:: or std::tr1::) for that. This means you can't have an STL container of auto_ptrs
, among other things. auto_ptr<>
is very useful for when you will have one copy of an object, with a limited lifetime. If you copy to another auto_ptr<>
, you lose the first. If you pass out the pointers, you have an excellent chance of trying to use an object that's already been deleted.
You can call SetOponent(*Class);
if you like, as that will pass the actual item (you pass objects, not pointers, to references). If you pass to a pointer, you could call with SetOpponent(Class.get())
. You'll still have the problem that the MyClass will be deleted when Class goes out of scope.