Thanks laserlight,
1.
I am interested to see how to use auto_ptr to achieve the effect of polynorphism. I have written the below code, do you think it is correct to demo this feature?
If yes, I think when we call pb->f(), the conversion operator of auto_ptr converts auto_ptr<Base> type to Base* type? My confusion is I have not seen auto_ptr has such a conversion operator to do such work. :-)
Code:
#include <iostream>
#include <memory>
using namespace std;
class Base
{
public:
virtual void f()
{
cout << "Base" << endl;
}
};
class Derived : public Base
{
public:
virtual void f()
{
cout << "Derived" << endl;
}
};
int main()
{
auto_ptr<Base> pb (new Derived);
pb->f(); // display derived
return 0;
}
2.
How do you define own another component? Manage the life cycle (responsible for creating and destroying)? Or have some other points?
Originally Posted by
laserlight
Yes. Basically, it says that each Goo object owns a Foo object. If you want each Goo object to own a Foo object that may actually be of a type derived from Foo, then you should store a std::tr1::shared_ptr, a std::auto_ptr or a raw pointer to Foo instead so that polymorphism will work. If you use a std::auto_ptr, then your Goo object will not have normal copying semantics. If you use a raw pointer, then you should implement the copy constructor, copy assignment operator and destructor appropriately.
If you need to refer to an existing instance, this "design" will not even work. You should store a reference, std::tr1::weak_ptr, or a raw pointer to the existing Foo object instead. If you use a raw pointer, then you run the risk of trying to access a non-existent object.
As you noted, "it depends".
regards,
George