boost :: smart_ptr可以用于多态吗?

Jon*_*han 8 c++ boost boost-smart-ptr

可以在多态中使用boost :: smart_ptr,如scoped_ptr和shared_ptr吗?

class SomeClass
{
public:
    SomeClass()
    {
        a_ptr.reset(new SubClass);
    }
private:
    boost::scoped_ptr<SuperClass> a_ptr;
}
Run Code Online (Sandbox Code Playgroud)

Jam*_*mes 6

我相信答案是肯定的; 对boost指针进行编码,以便在超类所在的任何地方都可以接受派生类.


Joh*_*ing 4

是的:

#include <string>
#include <iostream>
using namespace std;
#include <boost\shared_ptr.hpp>
using namespace boost;


class Foo
{
public:
    virtual string speak() const { return "Foo"; }
    virtual ~Foo() {};
};

class Bar : public Foo
{
public:
    string speak() const { return "Bar"; }
};

int main()
{
    boost::shared_ptr<Foo> my_foo(new Bar);
    cout << my_foo->speak();
}
Run Code Online (Sandbox Code Playgroud)

输出是:Bar