如何将抽象 class 作为函数参数传递,然后在原始超出范围后使用?

How to pass an abstract class as function parameter, which will then be used after the original goes out of scope?

我有以下摘要class

struct Interface {
    virtual ~Interface() = default;
    virtual void Do() = 0;
};

我有一个或多个具体 class 实现了 Interface

struct ImplA final: Interface{
    virtual void Do() override {printf("DO IN ImplA\n");}
};

struct ImplB final: Interface{
    virtual void Do() override {printf("DO IN ImplB\n");}
};

这是我的主要代码(只是抽象出来的)

int main() {
    {
        ImplA implA{};
        Method(implA);
        ImplB implB{};
        Method(implB);
       // Goes out of scope
    }
    // some other stuff here
    return 0;
}

这是方法的样子 我使用了一个全局容器来表明它也存在于方法的范围之外。以后会用到

std::vector<std::unique_ptr<Container>> containers;
void Method(Interface& myInterfaceReference) {
    // to show that it lives out of scope of this method
    // how should the reference be passed to Container class
    // such that it can be used even after original instances are out of scope
    containers.emplace_back(new Container());
}

最后容器 class 是什么样子的。 ←这是我遇到困难的部分,并且对如何设计它的所有想法持开放态度。

struct Container {
    // I dont mind if it is newly created
    Interface& referenceToInterface;
    // What to do with the ctor, how to pass it
    Container(???) {}
    
    void UseInterface() {
    //Do Stuff with referenceToInterface
    }   
};

Container 中存储一个智能指针,以便它控制引用对象的生命周期:

struct Container {
    std::unique_ptr<Interface> pointerToInterface;
// What to do with the ctor, how to pass it

传递一个智能指针:

Container(std::unique_ptr<Interface> i)
    : pointerToInterface(std::move(i)) {}

How to pass an abstract class as function parameter, which will then be used after the original goes out of scope?

传递一个智能指针:

std::vector<Container> containers;
void Method(std::unique_ptr<Interface> i) {
    containers.emplace_back(std::move(i));


Method(std::make_unique<ImplA>());
Method(std::make_unique<ImplB>());