我有容器,其中包含std::vector<std::shared_ptr<Base> >
VEC shared_ptr的基類Base
,也該容器具有功能add(Base&& base)
- 通過使用std::move
運營商將基本對象,以VEC,但是派生轉移構造不調用,只調用基礎構造函數。的std ::招不來創建衍生的
如何解決:我應該將其轉換爲Derived,使用dynamic_cast<Derived*>(&base)
,之後使用std::move
。
問題:我是否需要嘗試轉換爲所有可能的派生類,然後使用std::move
?
class Base{
public:
virtual ~Base(){}
Base(const Base& base) = delete;
Base(Base&& base){
std::cout<<"base move\n";
}
Base(){}
virtual void func(){
std::cout<<"run func from BASE class\n";
}
};
class Derived: public Base{
public:
virtual ~Derived() = default;
Derived(Derived&& derived):Base(std::move(derived)){
std::cout<<"Derived move\n";
}
Derived():Base(){
}
virtual void func() override {
std::cout<<"run func from DERIVED class\n";
}
};
class Container{
std::vector<shared_ptr<Base> > vec;
public:
void add(Base&& base){
this->vec.push_back(std::make_shared<Base>(std::move(base)));
}
void addDerived(Base&& base){
//TRY ALL POSSIBLE CASTING???
this->vec.push_back(std::make_shared<Derived>(std::move(*(dynamic_cast<Derived*>(&base)))));
}
void print(){
for(auto& obj: vec){
obj->func();
}
}
};
int main() {
std::cout << "Create container and add using function `add`" << std::endl;
Container container;
container.add(Derived());
container.print();
std::cout << "Create container and add using function `addDerived`" << std::endl;
Container container_new;
container_new.addDerived(Derived());
container_new.print();
}
//Will print
Create container and add using function `add`
base move
run func from BASE class
Create container and add using function `addDerived`
base move
Derived move
run func from DERIVED class
謝謝!但在目前的情況下,我無法從接口傳遞shared_ptr。我將值傳遞給我的構造函數,其中輸入參數是initializer_list。請檢查我的更新! –