Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Naming convention for Object Ownership in Methods

Is there a way to code into the signature of a method, whether the object owner-ship changes or not? In Getter() and Setter() which take or return pointers, you never know if the object ownership changes or not.

What do you think about:

// Uses pConfiguration or creates its own copy - the ownership is un-touched
void ContainerClass:SetConfiguration( const Configuration* pConfiguration ) {}
// Takes the ownership of pConfiguration (and deletes it in the destructor)
void ContainerClass:PutConfiguration( Configuration* pConfiguration ) {}
// Returns a 'reference' and keeps the ownership (you must not delete it)
const Configuration* ContainerClass::GetConfiguration() {}
// Returns a _new_ object and transfers the ownership to you
Configuration* ContainerClass::TakeConfiguration() {}

So is Set() vs. Put() and Get() vs. Take() a way to code it, or would you use the type (const vs. non-const) - or do you know it from the context?

Best Regards,

Charly

like image 367
Charly Avatar asked Sep 17 '25 04:09

Charly


2 Answers

The best way of identifying in an interface that ownership is not changed is by not using pointers. Prefer references to pointers:

// Does not take ownership
void ContainerClass::SetConfiguration( const Configuration& config ) {}

// Does not release ownership
const Configuration& ContainerClass::getConfiguration() const {}

When you need to actually transfer ownership of memory it is better documenting it by names. If you really feel the crave to make it explicit in the signature, use the good-old std::auto_ptr:

void ContainerClass::SetConfiguration( std::auto_ptr<Configuration> cfg );
std::auto_ptr<Configuration> ContainerClass::CopyConfiguration() const;

The std::auto_ptr has the weird property that copy actually means transfer the ownership.

like image 73
David Rodríguez - dribeas Avatar answered Sep 18 '25 17:09

David Rodríguez - dribeas


  1. Write good documentation and comments (you can use doxygen)
  2. In Qt where functions often play with ownership methods called for example itemAt and takeAt and addXXX always transfer ownership which is reflected in documentation. So you can use get() / take() and set() / put(). Anyway, good docs is always helpful, even your functions names are self-explained.
like image 23
maverik Avatar answered Sep 18 '25 18:09

maverik