c – 方法中对象所有权的命名约定
发布时间:2020-12-16 09:33:46 所属栏目:百科 来源:网络整理
导读:有没有办法编码方法的签名,无论对象所有者是否发生变化?在获取或返回指针的Getter()和Setter()中,您永远不知道对象所有权是否发生了变化. 你有什么想法: // Uses pConfiguration or creates its own copy - the ownership is un-touchedvoid ContainerClas
有没有办法编码方法的签名,无论对象所有者是否发生变化?在获取或返回指针的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()和Put()以及Get()和Take()是一种编码方式,或者你会使用类型(const与非const) – 或者你是否从上下文中知道它? 最好的祝福, 查理 解决方法
在接口中识别所有权未更改的最佳方法是不使用指针.更喜欢引用指针:
// Does not take ownership void ContainerClass::SetConfiguration( const Configuration& config ) {} // Does not release ownership const Configuration& ContainerClass::getConfiguration() const {} 当您需要实际转移内存的所有权时,最好通过名称进行记录.如果你真的觉得在签名中明确表达它的渴望,那就使用好老的std :: auto_ptr: void ContainerClass::SetConfiguration( std::auto_ptr<Configuration> cfg ); std::auto_ptr<Configuration> ContainerClass::CopyConfiguration() const; std :: auto_ptr具有奇怪的属性,复制实际上意味着转移所有权. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |