Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax guidelines for taking ownership and releasing objects in C++

Tags:

c++

ownership

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:

  • take ownership
  • don't take ownership
  • share

and about return value:

  • release ('return by value' is in this group)
  • don't release
  • share

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.

like image 792
abyss.7 Avatar asked Nov 03 '11 09:11

abyss.7


1 Answers

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 transferred
  • shared_ptr - multiple owners, ownership may be transferred
  • scoped_ptr - single owner, ownership cannot be transferred
  • weak_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.

like image 198
larsmoa Avatar answered Oct 27 '22 01:10

larsmoa