C++ Dependency Injection – Use Pointer or Object?

cdependency-injection

While I am learning C++ based on how develop in modern PHP frameworks I decided to use the Dependency Injection pattern with services as Singletons.

For making myself clear let suppose we have the collowing classes:

class B {
  public:
    B(){};
}

class A{
  public:
    // Dependency Injecting class B into class A
    A(B b):b(b){}
  private:
   const B b;
}

So in this example I wondered if I will gain better performance if I used pointer instead of an Object. In other words would it be better if class A had been:

class A{
  public:
    // Dependency Injecting class B into class A
    A(B* b):b(b){}
  private:
   const B *b;
}

Also, what is the downside in the pointer-based approach?

Best Answer

So in this example I wondered if I will gain better performance if I used pointer instead of an Object.

No.

I will be very surprised if that is the case.

Also, what is the downside in the pointer-based approach?

You'll have to define ownership policy of the object that the pointer points to. If the client is expected to retain ownership of the object,

  1. The client of A has to make sure that the pointer is valid as long as the A object is alive.

  2. Behavior of A will be unpredictable since it depends on the client to make sure that the pointer stays valid.

If A is expected to take over ownership of the object,

  1. You'll have to make sure the object that the pointer points to is deleted before the A object is destructed.

  2. You'll have to make sure to follow The Rule of Three so that copy construction and copy assignment are dealt with correctly.