jeudi 6 août 2015

C++11 dependency injection in constructor with reference

Consider following code:

#include <stdio.h>
#include <memory>

class Sub{};

class SubImpl : public Sub {};

class A{
public:
    A(Sub & sub) : sub(sub){}

    void doSomething(){
        // ...
    };

private:
    Sub & sub;
};

std::unique_ptr<A> factory(){
    SubImpl sub;

    return std::unique_ptr<A>(new A(sub));
}

int main(){
    auto a = factory();

    a->doSomething();
}

This code have problem - Sub object lifetime is not same as A object, and A::sub reference is dangled.

In order to fix this, I can do:

  • pass by value
  • pass by const reference
  • use unique_ptr / shared_ptr or to use raw pointer

Is there any other way I can fix this?

Aucun commentaire:

Enregistrer un commentaire