Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express the usage of C++ arguments through method interfaces

Is there a common way to express the usage of arguments in C++? I want to implicitly tell the consumers of my class how the arguments they pass will be used by the class.

Examples:

  1. I own your argument (will clean it up)
  2. I will hold a reference to your argument during my lifetime (so you should NOT delete it while I'm stile alive)
  3. I will use your argument only during construction and won't hold a reference

Is there a common way to express these things simply using the method declaration? I think in the first case a std::auto_ptr would make sense. In the second case I usually take a pointer to avoid someone passing a value from the stack which would invalidate my reference quickly, or alternatively a shared_ptr. In the third case I take a reference to allow values from the stack.

How do you deal with this? Also is it necessary to rely on smart pointers here, or can one express such things simply by using naked references and pointers somehow?

like image 552
driAn Avatar asked Jan 25 '09 23:01

driAn


2 Answers

Our team has similar coding conventions to the ones you suggest:

1 - auto_ptr argument means that the class will take control of memory management for the object. (We don't use this much.)

2 - shared_ptr means that the class will probably use the argument for an extended period of time, and in particular may store off its own shared_ptr to the object.

3 - Plain reference means that the argument will only be used for the duration of the call.

We treat this as a coding standard. It isn't something we document for each and every call.

like image 122
David Norman Avatar answered Nov 15 '22 04:11

David Norman


I don't know if there is a common idiom, but I do know that the one sure-fire way that I provide this information is comments in the interface header. The users of the class won't always read them, won't always remember them, and they'll screw them up quicker than you can blink, but the information WILL be there.

Now, that being said, I've also taken to being against keeping references to something that some other piece of the system owns. It's not always practical (or sensible) to restructure so that your class owns everything (or doesn't keep references after a method call returns), but it's the safest way to do things, and either one is easier for the caller to understand.

The big problem with retaining references is that your callers will never remember that they aren't allowed to destroy these things, and you'll eventually end up with 'use of deleted object' type failures.

like image 42
Michael Kohne Avatar answered Nov 15 '22 04:11

Michael Kohne