shared_ptr 上的成员访问指针

Member access on shared_ptr to pointer

我有一个 class 需要有一个成员引用到抽象 class 接口,该接口不能在 class 构造函数中实例化。我希望这个引用是一个共享指针。因为我希望引用是一个接口,而且我不能在我的构造函数中实例化 shared_ptr 指向的对象,所以我必须创建一个 shared_ptr 指向接口实例的指针。

现在我想在 shared_ptr 上使用成员访问运算符->,但这非常难看,因为我每次都必须取消引用指针。

#include <iostream>
#include <memory>

class IFace {
public:
    virtual ~IFace() {};
    virtual void doSomething() = 0;
};

class A : public IFace {
public:
    A() {};
    ~A() {};
    virtual void doSomething() { std::cout << "Foo"; };
};

class B {
public:
    B() {};
    ~B() {};
    std::shared_ptr<IFace *> myA;
    void attachA(std::shared_ptr<IFace *> a) {
    this->myA = a;
    };

    void callDoSomethingFromIFace() {
    (*(this->myA))->doSomething();
    };
};

int main() {
    A a;
    B b;

    b.attachA(std::make_shared<A *>(&a));
    b.callDoSomethingFromIFace();
}

有没有办法像这样使用成员访问运算符->

this->myA->doSomething();

而不是

(*(this->myA))->doSomething();

不确定你为什么认为 [...] because the interface is an abstract class, a normal shared pointer will not compile because the interface does not have a constructor.

这很好用:

#include <iostream>
#include <memory>

class IFace {
public:
    virtual ~IFace() {};
    virtual void doSomething() = 0;
};

class A : public IFace {
public:
    A() {};
    ~A() {};
    virtual void doSomething() { std::cout << "Foo"; };
};

class B {
public:
    B() {};
    ~B() {};
    std::shared_ptr<IFace> myA;
    void attachA(std::shared_ptr<IFace> a) {
    this->myA = a;
    };

    void callDoSomethingFromIFace() {
     this->myA->doSomething();
    };
};

int main() {
    B b;
    std::shared_ptr<A> a = std::make_shared<A>();
    b.attachA(a);
    b.callDoSomethingFromIFace();
}