在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();
}
与其照你的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()
因为我看到了非虚拟析构函数,所以您可能想要研究何时使用虚拟析构函数,还需要研究0/3/5规则(如果尚未使用)。
无论如何,很好的问题和良好的MCVE。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句