在 C++ 中,如何在不使用 reset 和 new 的情况下使用纯抽象类的共享指针?
这个例子有点做作,但说明了我遇到的问题。
看看run()方法:reset有效,但注释掉的行不......
#include <iostream>
#include <map>
#include <memory>
using namespace std;
class Interf {
public:
virtual void doSomething()=0;
};
class Foo : public Interf {
public:
Foo() { cout << "Foo constructed\n"; }
shared_ptr<Interf> innerInterf;
void doSomething() {
cout << "Foo:doSomething()\n";
innerInterf->doSomething();
}
void run() {
cout << "run() called\n";
innerInterf.reset(new Bar()); // this works
//Bar b;
//innerInterf = make_shared<Interf>((Interf)b); // how can i get this to work?
}
class Bar : public Interf {
public:
Bar() { cout << "Bar constructed\n"; }
~Bar(){ cout << "Bar destroyed\n"; }
void doSomething() { cout << "Bar:doSomething()\n"; }
};
};
int main() {
Foo foo;
foo.run();
Interf *interf;
interf = &foo;
cout << "interf.doSomething()\n";
interf->doSomething();
}
Run Code Online (Sandbox Code Playgroud)
Kam*_*Cuk 22
而不是new Bar写make_shared<Bar>,因为你正在制作Bar,而不是Interf。
Bar b;
innerInterf = make_shared<Bar>(b); // copy constructed? (no idea if that is what you want?)
innerInterf = make_shared<Bar>(); // calls Bar::Bar()
Run Code Online (Sandbox Code Playgroud)
因为我看到了非虚拟析构函数,所以您可能想要研究何时使用虚拟析构函数,以及0/3/5 规则(如果您还没有的话)。
无论如何,好问题和好 MCVE。