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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With