He called dependency injection through constructor injection : class A receives the dependency as an argument to its constructor and saves the reference to the dependent class as a private variable.
There is an interesting introduction to wikipedia .
For const-correctness, I would write:
using T = int; class A { public: A(const T &thing) : m_thing(thing) {}
but the problem with this class is that it accepts references to temporary objects:
T t; A a1{t}; // this is ok, but... A a2{T()}; // ... this is BAD.
Better to add (minimum C ++ 11 required):
class A { public: A(const T &thing) : m_thing(thing) {} A(const T &&) = delete;
Anyway, if you change the constructor:
class A { public: A(const T *thing) : m_thing(*thing) { assert(thing); }
It is pretty much guaranteed that you will not have a pointer to a temporary one .
In addition, since the constructor accepts a pointer, it is more clear to users of A so that they pay attention to the lifetime of the transmitted object. Strike>
A few related topics:
- Should I prefer pointers or references in member data?
- Using reference as class members for dependencies
- Gotw # 88
- Disable rvalue binding through constructor to reference to Member constant
manlio Sep 15 '14 at 10:23 2014-09-15 10:23
source share