Search code examples
c++visual-studio-2012dependency-injectiongetter-setterunique-ptr

Getter and setter for unique_ptr object (dependency injection)


I have a class MyClass that owns an instance of some DataProvider class and has a getter for this.

For the sake of Dependency Injection I would prefer to have a getter and a setter. Additionally the DataProvider should be contained in a std::unique_pointer:

#include <memory>
#include <iostream>

class DataProvider
{
public:
    DataProvider() {}
    virtual ~DataProvider() {}
    /* stuff */

private:
    /* more stuff */

};

class MyClass
{
public:
MyClass() {}

    virtual inline const DataProvider &getDataProvider() const
    {
        return *data;
    }
    void setDataProvider(std::unique_ptr<DataProvider> newData)
    {
        data = std::move(newData);
    }

private:
    std::unique_ptr<DataProvider> data;
};

I've read this: How do I pass a unique_ptr argument to a constructor or a function?

But it does not cover the getter part. Is this (above) the right way to do this? What are alternatives to think of?


Solution

  • As you wrote

    virtual inline const DataProvider &getDataProvider() const
    {
        return *data;
    }
    void setDataProvider(std::unique_ptr<DataProvider> newData)
    {
        data = std::move(newData);
    }
    

    is perfectly OK. In the setter the class gets ownership of the DataProvider instance and never let go (as far as seen here).

    A full example has been given by sftrabbit here: http://ideone.com/enarAS