Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How does C++ achieve the effect of copying?

Shulou Source: shulou.com Published: 2022-06-01 19:11:53 10月02日 Update

This article mainly explains "how C++ can achieve the effect of copying". The content in the article is simple and clear, and it is easy to learn and understand. Now please follow the editor's train of thought slowly and deeply. Let's study and learn how C++ can achieve the effect of copying.

C.61: copy operation should have the effect of copy

Reason (reason)

This is a conventional semantics. When xroomy is executed, we should also think of it as xroomy. After copying the action, x and y can be two independent objects (value semantics, like non-pointer built-in types and standard library types) or different references to the same shared object (pointer semantics, like pointer behavior).

Example (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 Xa, const Xb)

{

Return a.sz = = b.sz & & equal (A.P, A.P + a.sz, b.p, b.p + b.sz)

}

XRV X (const Xa)

: 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 semanticsExample (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 semanticsNote (note)

Unless you are building some kind of "smart pointer", the value semantics is better. Value semantics are the easiest to understand and are expected by the standard library function.

Thank you for your reading. the above is the content of "how to achieve the effect of copying on C++". After the study of this article, I believe you have a deeper understanding of how to achieve the effect of copying on C++. The specific use also needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Tags: Copy effect semantics caching pointer a.p learning content object standard example type difference convention two function action reason that is idea Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS Shulou Information Shulou Tech Info vpn Apple