C++ Coding Style – unique_ptr and References Best Practices

ccoding-style

I'm pretty sure this is a question purely about aesthetics but I wanted to get all your opinions on it before I start proliferating this type of code in my codebase. Consider the following code:

//Foo.h
class Bar;
class Foo
{
    public:
       Bar& GetBar(){return *bar.get();}
    private:
       std::unique_ptr<Bar> bar;
};

//Bar.h
class Bar
{
     public:
         DoSomething(){//did something...}
};

This allows us to forward declare Bar in Foo.h and avoid having to #include Bar.h.
This leads to using Foo's Bar in the following way:

Foo foo;
foo.GetBar().DoSomething();

Personally, I think this would look a lot nicer:

Foo foo;
foo.bar.DoSomething();

To achieve that, I've written:

//Foo.h
class Bar;
class Foo
{
    public:
        Foo();
        Bar& bar;
    private:
        std::unique_ptr<Bar> bar_ptr;
};

//Foo.cpp
#include "Bar.h"
Foo::Foo() : bar_ptr(new Bar()), bar(*bar_ptr) {}

This allows me to forward declare Bar and use the 'bar.' syntax.

Ugly? Not Ugly? The downside is that I have 2 member vars for only 1 object.

Best Answer

foo.GetBar().DoSomething();

This violates the Law Of Demeter.

Generally I would avoid exposing Bar entirely:

foo::doBarSomething() { this->bar.doSomething(); }
Related Topic