Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make data ownership explicit in C++

Tags:

c++

When working with pointers and references in C++, it is sometimes difficult to see whether the pointer has ownership over the referenced data, or if it is just a temporal reference. For example:

Instance* i = new Instance();
Instance* j = i;

How can it be made clear which of the 2 pointers has ownership over the instance? In other words, how to make clear on which pointer delete has to be called?

Note: In the above example this is not hard to see, as it is a very short piece of code. However, when the pointer is duplicated and passed around a lot, this can become unclear.

like image 495
Dimitri C. Avatar asked Jun 24 '09 13:06

Dimitri C.


2 Answers

You cannot determine the owner, since there is no built in mechanism to know which pointer is owning the memory the pointer points to.

If you are really concerned about this, you could always introduce your own naming convention, e.g. through some pre/post-fix to your variable names. In other words, it's your code design that can give you this information. Since you (and your coworkers) are writing the code you can always make sure that this design is enforced during implementation. This of course means that everyone has to follow these "rules".

This is one reason why a common coding convention is so important. So you can read your own and other peoples code and understand it.

like image 105
ralphtheninja Avatar answered Sep 30 '22 21:09

ralphtheninja


Firstly, it seems unnecessarily confounding to use a reference to refer to data that must be deleted. Use a pointer instead.

Secondly, if you want to indicate ownership of an object, use a wrapper class that manages ownership. There is auto_ptr specifically for this purpose, although it has shortcomings. (These should be addressed by unique_ptr in the next version of the language, though that doesn't help you now).

Thirdly, in the simplest cases (as often as possible), don't use the heap directly. Just declare a local object, e.g.

std::vector<int> v;

This doesn't stop you transfering ownership when you need to (use swap).

like image 44
Daniel Earwicker Avatar answered Sep 30 '22 22:09

Daniel Earwicker