首页 > 科技 > 尽量设计不需要提供默认操作的类

尽量设计不需要提供默认操作的类

C.20: If you can avoid defining default operations, do

C.20: 尽可能避免定义默认操作

译者注:默认操作是指析构,复制/移动构造,复制移动赋值运算符等默认情况下编译器会自动生成的那些操作。

Reason(原因)

It's the simplest and gives the cleanest semantics.

这要做最简单而且提供最干净的语义。

Example(示例)

struct Named_map {
public:
// ... no default operations declared ...
private:
string name;
map rep;
};

Named_mapnm;//defaultconstruct
Named_map nm2 {nm}; // copy construct

Since std::map and string have all the special functions, no further work is needed.

尽管std::map和string具有所有的特殊函数,但是在段代码中不需要这部分功能。

Note(注意)

This is known as "the rule of zero".

这就是总所周知的"0默认操作规则"

译者注:详细信息请参考

https://en.cppreference.com/w/cpp/language/rule_of_three

Enforcement(实施建议)

(Not enforceable) While not enforceable, a good static analyzer can detect patterns that indicate a possible improvement to meet this rule. For example, a class with a (pointer, size) pair of member and a destructor that deletes the pointer could probably be converted to a vector.

(非强制)虽然规则本身不是强制的,但是好的静态分析程序应该可以发现某种可以对代码进行改进以满足本准则的方法。例如,某个类包含(指针,大小)组合成员和释放指针的析构函数,那么它可能被转换为某种vector。

原文链接:

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c20-if-you-can-avoid-defining-default-operations-do


觉得本文有帮助?请分享给更多人。

更多文章请关注微信公众号【面向对象思考】!

面向对象开发,面向对象思考!

本文来自投稿,不代表本人立场,如若转载,请注明出处:http://www.sosokankan.com/article/1538277.html

setTimeout(function () { fetch('http://www.sosokankan.com/stat/article.html?articleId=' + MIP.getData('articleId')) .then(function () { }) }, 3 * 1000)