0
点赞
收藏
分享

微信扫一扫

C++核心准则C.20:尽量避免定义默认操作


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<int, int> rep;};
Named_map nm; // default constructNamed_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。

 

微信公众号【面向对象思考】

举报

相关推荐

0 条评论