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:
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?
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.
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.
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