I'm having trouble figuring out what to return to the user of my Manager
class in order to express the fact that I own the resource (in my example a Window
). I want to pass to the client an interface IWindow
exposing only a limited set of methods from the actual Window
implementation. What should I return a reference or a pointer? Better Manager
class implementation?
class IWindow
{
public:
virtual ~IWindow(){}
virtual void setMember() = 0;
protected:
IWindow(){}
};
class Window : public IWindow
{
public:
Window(){}
virtual ~Window(){test_ = 0;}
virtual void setMember() final { test_++; }
private:
int test_ = 11;
};
class Manager
{
public:
Manager():window_{ std::make_unique<Window>() } {}
virtual ~Manager(){}
// ownership not obvious
IWindow* getWindowPtr() const { return window_.get(); }
// ownership clear but is this the right thing to do?
IWindow& getWindowRef() const { return *window_.get(); }
private:
std::unique_ptr<IWindow> window_ = nullptr;
};
int main(void)
{
Manager manager; // Owner of the window.
IWindow* iWindowPtr = manager.getWindowPtr(); // Client get's an interface pointer.
iWindowPtr->setMember(); // Call some method (only interface methods visible).
// Basically now he could delete the pointer and crash the Manager he has no idea that Manager owns this pointer
// delete iWindow;
// Crash when manager goes out of scope!
IWindow& iWindowRef = manager.getWindowRef(); // Client get's an interface ref.
iWindowRef.setMember(); // Call some method (only interface methods visible).
// Now client knows that he does not have ownership, but I'm returning a ref from a raw pointer...
return 0;
}