How about the ownership of the transferred object being transferred to the dependent object. This will solve the problem of life expectancy for the composition, avoiding the use of smart pointers. But for difficult situations, when owning important smart pointers will be a choice.
class Car { public: Car(IEngine *pEngine) { m_pEngine = pEngine; } ... ~Car() { delete m_engine; } protected: IEngine *m_pEngine; }
In cases where the dependency undoubtedly has a shorter lifetime than the injected object, it is better to pass the embedded object as a reference. This will clearly indicate that the injected object does not belong to the dependent object.
source share