-
assignment to auto_ptr
Hi,
I am learning to use auto_ptr.
my question is in purple comments below.
Code:
#include <iostream>
using namespace std;
class Base
{
public:
virtual void print()=0;
};
class A : public Base
{
public:
void print() { cout << "A" << endl; }
};
class B : public Base
{
public:
void print() { cout << "B" << endl; }
};
int main()
{
auto_ptr<Base> owner;
if(5==5)
{
A* a = new A;
owner = a; // this was my first guess, does not compile though.
owner = auto_ptr<Base>(a); // this compiles. is this how you do it?
}
else
{
B* b = new B;
owner = auto_ptr<Base>(b);
}
owner->print();
return 0;
}
-
Yes, the second way is correct. You could just write:
Code:
owner = auto_ptr<Base>(new A);
Incidentally, I believe you should #include <memory> for std::auto_ptr.
-
-
You should do
Code:
owner.reset(new A);
-
Quote:
Originally Posted by
CornedBee
You should do
Code:
owner.reset(new A);
Why? isn't it the same?
-
No, it avoids constructing a new auto_ptr and then copy-assigning it into the current one. Now, compilers might be able to optimize the additional copy away - but then, they might not.
In any case, the reset() is the most common way of setting a smart pointer to a new value.
-
>Why?
It's shorter and more directly reflects your intentions?
-
Quote:
Originally Posted by
kroiz
Why? isn't it the same?
not exactly
Code:
owner = auto_ptr<Base>(new A);
creates an unnecessary temporary auto_ptr that is then assigned to owner.
Kurt
-
Understood.
Thanks you all.
-
Is it the same with boost::shared_ptr regarding .reset() thing?
-
Yes. reset() allows smart pointers to take ownership of an object by swapping it into its this pointer. That's all reset does, and you should use it.