I want to know - are there any guidelines about syntax of C++ (non-)member functions, that allows me to understand (without comments, if possible) the ownership policy of its arguments and return value. By ownership I mean, that the owner is responsible for the destruction of the owned object.
I distinguish the following rules about arguments:
and about return value:
For example, passing object by reference doesn't take it's ownership:
void func(object & obj) { ... }
Such guidelines may use standard constructions like unique_ptr, shared_ptr, etc. If there are no such guidelines, then the examples of possible syntax misunderstandings are welcome too.
I can't see why using smart pointers doesn't suffice. I can't think of anything else that I wouldn't categorize as code smell. Using smart pointers over raw pointers makes ownership and responsebilities perfectly clear:
auto_ptr
/unique_ptr
- single owner, ownership is transferredshared_ptr
- multiple owners, ownership may be transferredscoped_ptr
- single owner, ownership cannot be transferredweak_ptr
- observer (but shared_ptr
may be created from weak_ptr
)I think that these suffice to clearly show the responsibilities, e.g.
void func(std::auto_ptr<Class> input) {...} // func() takes ownership of input
void func(std::shared_ptr<Class> input) {...} // func() and caller share ownership
std::auto_ptr<Class> func() {...} // caller takes ownership of returned value
std::shared_ptr<Class> func() {...} // func() and caller shares ownership of returned object
std::weak_ptr<Class> func() {...} // func() owns created object, but caller may observe it
As you mention, references are also great in this sense. Note if there's a need to free the pointers using some custom mechanism, shared_ptr
and unique_ptr
supports custom deleters. auto_ptr
does not have this capability.
Note! If you are using C++ pre-11, you'll have to resort to boost::shared_ptr
and boost:weak_ptr
.
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