Member access on shared_ptr to pointer

685 views Asked by At

I have a class which needs to have a member reference to an abstract class interface that cannot be instantiated in the class constructor. I want this reference to be a shared pointer. Because I want the reference to be to an interface, and I cannot instantiate the object pointed to by the shared_ptr in my constructor, I have to make a shared_ptr to a pointer to an instance of the interface.

Now I want to use the member access operator-> on the shared_ptr, but this is quite ugly because I have to dereference the pointer every time.

#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();
}

Is there a way to use the member access operator-> like so

this->myA->doSomething();

Instead of

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

There are 1 answers

4
t.niese On BEST ANSWER

Not sure why you assume that [...] because the interface is an abstract class, a normal shared pointer will not compile because the interface does not have a constructor.

This works perfectly fine:

#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();
}