【发布时间】:2011-07-27 11:41:37
【问题描述】:
有没有办法在方法的签名中编码,无论对象所有权是否改变?在获取或返回指针的 Getter() 和 Setter() 中,您永远不知道对象所有权是否发生变化。
你怎么看:
// 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() {}
Set() vs. Put() 和 Get() vs. Take() 也是一种编码方式,或者您会使用类型(const vs. non-const) - 还是您从上下文?
最好的问候,
查理
【问题讨论】:
-
你检查过智能指针吗?它将避免这些类型的问题。
-
嗯......它解决了删除问题......但它仍然没有说明对象所有权。我必须考虑 - 如果它解决了我所有的问题:)
标签: c++ oop naming-conventions