在C ++中获取所有权和释放对象的语法准则 [英] Syntax guidelines for taking ownership and releasing objects in C++
问题描述
我想知道 - 有关于C ++(非)成员函数的语法的任何指导,允许我理解(无论如何,如果可能的话)其参数和返回值的所有权策略。
I want to know - are there any guidelines about syntax of C++ (non-)member functions, that allows me to understand (without comments, if possible) the ownership policy of its arguments and return value. By ownership I mean, that the owner is responsible for the destruction of the owned object.
我区分以下关于参数的规则:
I distinguish the following rules about arguments:
- 取得所有权
- 不占有所有权
- 分享
和关于返回值:
- 不发布
- 分享
<在此群组中)
例如,通过引用传递对象不会取得所有权:
For example, passing object by reference doesn't take it's ownership:
void func(object & obj) { ... }
这样的指南可以使用标准结构,如unique_ptr,shared_ptr等。
Such guidelines may use standard constructions like unique_ptr, shared_ptr, etc. If there are no such guidelines, then the examples of possible syntax misunderstandings are welcome too.
推荐答案
我不明白为什么要使用智能指针不够。我不能想到任何其他我不会归类为代码气味。在原始指针上使用智能指针使所有权和响应能力完全清楚:
I can't see why using smart pointers doesn't suffice. I can't think of anything else that I wouldn't categorize as code smell. Using smart pointers over raw pointers makes ownership and responsebilities perfectly clear:
-
auto_ptr
unique_ptr
- 单个所有者,所有权已转移 -
shared_ptr
-
-
scoped_ptr
- 单个拥有者,无法转移所有权 c $ c> weak_ptr - observer(但是
shared_ptr
可以从 weak_ptr
)创建 auto_ptr
/unique_ptr
- single owner, ownership is transferredshared_ptr
- multiple owners, ownership may be transferredscoped_ptr
- single owner, ownership cannot be transferredweak_ptr
- observer (butshared_ptr
may be created fromweak_ptr
)
我认为这些足以清楚地显示责任,例如
I think that these suffice to clearly show the responsibilities, e.g.
void func(std::auto_ptr<Class> input) {...} // func() takes ownership of input
void func(std::shared_ptr<Class> input) {...} // func() and caller share ownership
std::auto_ptr<Class> func() {...} // caller takes ownership of returned value
std::shared_ptr<Class> func() {...} // func() and caller shares ownership of returned object
std::weak_ptr<Class> func() {...} // func() owns created object, but caller may observe it
正如你所提到的,在这个意义上,引用也很大。注意,如果需要使用一些自定义机制释放指针, shared_ptr
和 unique_ptr
支持自定义删除程序。 auto_ptr
没有此功能。
As you mention, references are also great in this sense. Note if there's a need to free the pointers using some custom mechanism, shared_ptr
and unique_ptr
supports custom deleters. auto_ptr
does not have this capability.
注意!如果你使用的是C ++ 11之前的版本,你必须使用 boost :: shared_ptr
和 boost:weak_ptr
。
Note! If you are using C++ pre-11, you'll have to resort to boost::shared_ptr
and boost:weak_ptr
.
这篇关于在C ++中获取所有权和释放对象的语法准则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!