【发布时间】:2019-02-17 19:28:08
【问题描述】:
我有一个 C++ 代码,我尝试在派生类上创建 shared_pointer。当shared_pointer 创建时,动态调度停止工作。
我的代码:
#include <iostream>
#include <memory>
using namespace std;
template <typename T>
class Base
{
public:
virtual void print()
{
cout << "Print from Base" << endl;
}
};
template <typename T>
class Child : public Base<T>
{
public:
virtual void print()
{
cout << "Print from Child" << endl;
}
};
template <typename T>
class TestClass: public Base<T>
{
public:
TestClass<T> (Base<T> &b)
{
b.print();
shared_ptr<Base<T>> sptr = make_shared<Base<T>> (b);
sptr->print();
}
};
int main()
{
Child<int> child;
TestClass<int> cl(child);
}
在TestClass的拷贝构造函数中,我先调用了print()方法,效果很好。创建shared_pointer 后,该方法将引用基类。
输出如下:
Print from Child
Print from Base
问题:如何创建共享指针而不丢失动态调度功能?
【问题讨论】:
-
这是因为你正在构造一个新的基类,而不是一个带有复制构造函数的新子类。
-
听起来好像这个人在找
shared_from_this?
标签: c++ inheritance polymorphism shared-ptr