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)开发者_JAVA百科
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.
- Write good documentation and comments (you can use doxygen)
- In Qt where functions often play with ownership methods called for example
itemAt
andtakeAt
andaddXXX
always transfer ownership which is reflected in documentation. So you can useget()
/take()
andset()
/put()
. Anyway, good docs is always helpful, even your functions names are self-explained.
Most of the time, when using pointers, there is no "ownership" to begin with, so there's no issue of it changing. But design is the key; the role of the class should make clear its relationship with the object pointed to. At a higher level than ownership or whatever. And that relationship, in turn, determines what it will do with the object.
For the exceptional cases where ownership is relevant, std::auto_ptr
is the standard way of expressing transfer. It's an absolute transfer,
though; if the parameter has a type std::auto_ptr
, then the caller
cannot even access the object once he's called the function. (I've
found this very effective in threading scenarios. It does make sense
for an object to be owned by a specific thread, at any given time, and
that no other thread can access it, and std::auto_ptr
expresses this
very clearly and effectively.)
精彩评论