Search code examples
c++referenceauto-ptr

References and auto_ptr


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?


Solution

  • 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.