Example:
class Bar;
class Foo
{
public:
Foo(const Bar& bar) : mBar(&bar) {}
/* Other methods use mBar. */
private:
const Bar* mBar;
};
So the goal is to store a const pointer to some external object, not to store a copy of the external object's contents.
- Pass by const reference:
Foo(const Bar& bar)- Common idiom to pass a object to a constructor, many programmers will think the Foo will store a copy of the Bar rather then the pointer/reference itself.
- Caller can pass a temporary. This can be prevented by deleting the r-value overload
Foo(const Bar&&) = delete. However this isn't fool-proof as you can still smuggle in temporaries via a function that takes a const reference and returns a const reference.Foo afoo(std::min(Bar{}, anotherBar));for example.
- Pass by const pointer:
Foo(const Bar* bar)- Must check for nullptr, which is a runtime check, compile time mechanisms are preferred.
- Can still smuggle in temporaries:
Foo afoo(&std::min(Bar{}, anotherBar));
Which of the above is preferred and why? Or are there any better ways to do this that do not suffer from the above problems ?
You can accept a
::std::reference_wrapper<Bar>, it will handle case with passing an rvalue as well as provide a hint that you are aming to copy wrapper rather than the object.