In C++11, you can use a shared_ptr<>
to establish an ownership relation with an object or variable and weak_ptr<>
to safely reference t
boost::optional<Trebuchet&>
As Billy ONeal pointed out in his answer you likely want to pass a Trebuchet&
instead of a pointer. The problem with the reference is that you cannot pass a nullptr
, boost::optional
provides a way to have the equivilent of a nullptr
. Further details on boost::optional are here: http://www.boost.org/doc/libs/1_54_0/libs/optional/doc/html/boost_optional/detailed_semantics.html
See also this question: boost::optional<T&> vs T*
Note: std::optional<T>
is on track to make it into C++14 but std::optional<T&>
is a separate proposal that is not in the current C++14 draft. Further details here: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3672.html
There is a genuine need for a standard pointer type to act as a non-owning, inexpensive, and well-behaved counterpoint to std::unique_ptr<>
. No such pointer has been standardized yet, but a standard has been proposed and is under discussion by the C++ standards committee. The "World's Dumbest Smart Pointer", aka std::exempt_ptr<>
would have the general semantics of other modern C++ pointer classes but would hold no responsibility either for owning the pointed-to object (as shared_ptr
and unique_ptr
do) or for correctly responding to the deletion of that object (as weak_ptr
does).
Assuming that this feature is ultimately ratified by the committee, it would fully meet the need highlighted in this question. Even if it isn't ratified by the committee, the above linked document fully expresses the need and describes a complete solution.