C++核心准则C.61:拷贝操作应该具有拷贝的效果

共 1793字,需浏览 4分钟

 ·

2020-01-09 23:26

f1cfa829a777358de750fa6b89b2ef7c.webp

C.61: A copy operation should copy

C.61:拷贝操作应该具有拷贝的效果


380c556b84aa4f07b45bfc682f717da6.webpReason(原因)

That is the generally assumed semantics. After x = y, we should have x == y. After a copy x and y can be independent objects (value semantics, the way non-pointer built-in types and the standard-library types work) or refer to a shared object (pointer semantics, the way pointers work).

这是一个约定俗成的语义。当x=y被执行之后,我们应该也可以认为x==y。拷贝动作之后,x和y可以是独立的两个对象(值语义,象非指针内置类型和标准库类型那样)或者同一个共享对象的不同参照(指针语义,象指针的行为那样)。


380c556b84aa4f07b45bfc682f717da6.webpExample(示例)
class X {   // OK: value semantics
public:
   X();
   X(const X&);     // copy X
   void modify();   // change the value of X
   // ...
   ~X() { delete[] p; }
private:
   T* p;
   int sz;
};

bool operator==(const X& a, const X& b)
{
   return a.sz == b.sz && equal(a.p, a.p + a.sz, b.p, b.p + b.sz);
}

X::X(const X& a)
   :p{new T[a.sz]}, sz{a.sz}
{
   copy(a.p, a.p + sz, p);
}

X x;
X y = x;
if (x != y) throw Bad{};
x.modify();
if (x == y) throw Bad{};   // assume value semantics
380c556b84aa4f07b45bfc682f717da6.webpExample(示例)
class X2 {  // OK: pointer semantics
public:
   X2();
   X2(const X2&) = default; // shallow copy
   ~X2() = default;
   void modify();          // change the pointed-to value
   // ...
private:
   T* p;
   int sz;
};

bool operator==(const X2& a, const X2& b)
{
   return a.sz == b.sz && a.p == b.p;
}

X2 x;
X2 y = x;
if (x != y) throw Bad{};
x.modify();
if (x != y) throw Bad{};  // assume pointer semantics
380c556b84aa4f07b45bfc682f717da6.webpNote(注意)

Prefer value semantics unless you are building a "smart pointer". Value semantics is the simplest to reason about and what the standard-library facilities expect.

除非你在构建某种“智能指针,否则值语义更好。值语义最容易理解而且也是标准库功能期待的。


380c556b84aa4f07b45bfc682f717da6.webpEnforcement(实施建议)

(Not enforceable)无


380c556b84aa4f07b45bfc682f717da6.webp原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c61-a-copy-operation-should-copy




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

关注【面向对象思考】轻松学习每一天!

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

浏览 15
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报