shared_ptr上的成员访问指针

时间:2018-02-12 09:00:34

标签: c++ shared-ptr

我有一个类,它需要对一个抽象类接口的成员引用,该接口无法在类构造函数中实例化。我希望这个引用是一个共享指针。因为我希望引用是一个接口,并且我无法实例化构造函数中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();
}

有没有办法使用会员访问运营商 - &gt;像这样

this->myA->doSomething();

而不是

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

1 个答案:

答案 0 :(得分:1)

不确定为什么假设[...] 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();
}