C.61: A copy operation should copy
C.61:拷贝操作应该具有拷贝的效果
Reason(原因)
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可以是独立的两个对象(值语义,象非指针内置类型和标准库类型那样)或者同一个共享对象的不同参照(指针语义,象指针的行为那样)。
Example(示例)
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
Example(示例)
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
Note(注意)
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.
除非你在构建某种“智能指针”,否则值语义更好。值语义最容易理解而且也是标准库功能期待的。
Enforcement(实施建议)
(Not enforceable)无
原文链接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c61-a-copy-operation-should-copy
觉得本文有帮助?请分享给更多人。
关注【面向对象思考】轻松学习每一天!
面向对象开发,面向对象思考!