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