SlideShare a Scribd company logo
1 of 12
Copy
Move
‫کردن‬ ‫فعال‬ ‫غیر‬Copy‫و‬Move
01. void test(complex z1)
02. {
03. complex z2(z1); // Copy initialization
04. complex z3;
05. z3 = z2; // Copy assignment
06. // ...
07. }
01. void bad_copy(Vector v1)
02. {
03. Vector v2 = v1; // Copy v1's representation into v2
04. v1[0] = 2; // v2[0] is now also 2!
05. v2[1] = 3; // v1[1] is now also 3!
06. }
01. class Vector {
02. private:
03. // elem points to an array of sz doubles
04. double* elem;
05. int sz;
06. public:
07. Vector(int s); // Constructor
08. ~Vector() { delete[] elem; } // Destructor
09.
10. Vector(const Vector& a); // Copy constructor
11. Vector& operator=(const Vector& a); // Copy assignment
12.
13. double& operator[](int i);
14. const double& operator[](int i) const;
15. int size() const;
16. };
01. Vector::Vector(const Vector& a) // Copy constructor
02. : elem(new double[sz]) // Allocate space for elements
03. , sz(a.sz)
04. {
05. for (int i = 0; i != sz; ++i) // Copy elements
06. elem[i] = a.elem[i];
07. }
01. // Copy assignment
02. Vector& vector::operator=(const Vector& a)
03. {
04. double* p = new double[a.sz];
05. for (int i = 0; i != a.sz; ++i)
06. p[i] = a.elem[i];
07. delete[] elem;
08. elem = p;
09. sz = a.sz;
10. return *this;
11. }
01. Vector operator+(const Vector& a, const Vector& b)
02. {
03. if (a.size() != b.size())
04. throw Vector_size_mismatch();
05. Vector res(a.size());
06. for (int i = 0; i != a.size(); ++i)
07. res[i] = a[i] + b[i];
08. return res;
09. }
01. void f(const Vector& x, const Vector& y, const Vector& z)
02. {
03. Vector r;
04. // ...
05. r = x + y + z;
06. // ...
07. }
01. class Vector {
02. // ...
03. Vector(const Vector& a); // Copy constructor
04. Vector& operator=(const Vector& a); // Copy assignment
05.
06. Vector(Vector&& a); // Move constructor
07. Vector& operator=(Vector&& a); // Move assignment
08. };
09.
10. Vector::Vector(Vector&& a)
11. : elem(a.elem) // "grab the elements" form a
12. , sz(a.sz)
13. {
14. a.elem = nullptr; // Now a has no elements
15. a.sz = 0;
16. }
01. Vector f()
02. {
03. Vector x(1000);
04. Vector y(1000);
05. Vector z(1000);
06. // ...
07. z = x; // We get a copy
08. y = std::move(x); // We get a move
09. // ...
10. return z; // We get a move
11. }
01. class Shape {
02. public:
03. // No copy operations
04. Shape(const Shape&) = delete;
05. Shape& operator=(const Shape&) = delete;
06.
07. // No move operations
08. Shape(Shape&&) = delete;
09. Shape& operator=(Shape&&) = delete;
10.
11. ~Shape();
12. // ...
13. };
10. copy and move

More Related Content

More from Vahid Heidari (9)

11. template
11. template11. template
11. template
 
9. class hierarchies
9. class hierarchies9. class hierarchies
9. class hierarchies
 
7. abstraction mechanisms, containers
7. abstraction mechanisms, containers7. abstraction mechanisms, containers
7. abstraction mechanisms, containers
 
6. separation, namespace, error
6. separation, namespace, error6. separation, namespace, error
6. separation, namespace, error
 
5. struct, class, enum
5. struct, class, enum5. struct, class, enum
5. struct, class, enum
 
4. pointers, arrays
4. pointers, arrays4. pointers, arrays
4. pointers, arrays
 
3. tests, loops
3. tests, loops3. tests, loops
3. tests, loops
 
2. types, vars, arith, consts
2. types, vars, arith, consts2. types, vars, arith, consts
2. types, vars, arith, consts
 
1. preface, hello world
1. preface, hello world1. preface, hello world
1. preface, hello world
 

Recently uploaded

Jax, FL Admin Community Group 05.14.2024 Combined Deck
Jax, FL Admin Community Group 05.14.2024 Combined DeckJax, FL Admin Community Group 05.14.2024 Combined Deck
Jax, FL Admin Community Group 05.14.2024 Combined Deck
Marc Lester
 
Abortion Pills For Sale WhatsApp[[+27737758557]] In Birch Acres, Abortion Pil...
Abortion Pills For Sale WhatsApp[[+27737758557]] In Birch Acres, Abortion Pil...Abortion Pills For Sale WhatsApp[[+27737758557]] In Birch Acres, Abortion Pil...
Abortion Pills For Sale WhatsApp[[+27737758557]] In Birch Acres, Abortion Pil...
drm1699
 

Recently uploaded (20)

Abortion Clinic In Springs ](+27832195400*)[ 🏥 Safe Abortion Pills in Springs...
Abortion Clinic In Springs ](+27832195400*)[ 🏥 Safe Abortion Pills in Springs...Abortion Clinic In Springs ](+27832195400*)[ 🏥 Safe Abortion Pills in Springs...
Abortion Clinic In Springs ](+27832195400*)[ 🏥 Safe Abortion Pills in Springs...
 
Alluxio Monthly Webinar | Simplify Data Access for AI in Multi-Cloud
Alluxio Monthly Webinar | Simplify Data Access for AI in Multi-CloudAlluxio Monthly Webinar | Simplify Data Access for AI in Multi-Cloud
Alluxio Monthly Webinar | Simplify Data Access for AI in Multi-Cloud
 
Jax, FL Admin Community Group 05.14.2024 Combined Deck
Jax, FL Admin Community Group 05.14.2024 Combined DeckJax, FL Admin Community Group 05.14.2024 Combined Deck
Jax, FL Admin Community Group 05.14.2024 Combined Deck
 
Abortion Pill Prices Turfloop ](+27832195400*)[ 🏥 Women's Abortion Clinic in ...
Abortion Pill Prices Turfloop ](+27832195400*)[ 🏥 Women's Abortion Clinic in ...Abortion Pill Prices Turfloop ](+27832195400*)[ 🏥 Women's Abortion Clinic in ...
Abortion Pill Prices Turfloop ](+27832195400*)[ 🏥 Women's Abortion Clinic in ...
 
A Deep Dive into Secure Product Development Frameworks.pdf
A Deep Dive into Secure Product Development Frameworks.pdfA Deep Dive into Secure Product Development Frameworks.pdf
A Deep Dive into Secure Product Development Frameworks.pdf
 
Community is Just as Important as Code by Andrea Goulet
Community is Just as Important as Code by Andrea GouletCommunity is Just as Important as Code by Andrea Goulet
Community is Just as Important as Code by Andrea Goulet
 
GraphSummit Milan - Neo4j: The Art of the Possible with Graph
GraphSummit Milan - Neo4j: The Art of the Possible with GraphGraphSummit Milan - Neo4j: The Art of the Possible with Graph
GraphSummit Milan - Neo4j: The Art of the Possible with Graph
 
OpenChain Webinar: AboutCode and Beyond - End-to-End SCA
OpenChain Webinar: AboutCode and Beyond - End-to-End SCAOpenChain Webinar: AboutCode and Beyond - End-to-End SCA
OpenChain Webinar: AboutCode and Beyond - End-to-End SCA
 
Abortion Pill Prices Jane Furse ](+27832195400*)[ 🏥 Women's Abortion Clinic i...
Abortion Pill Prices Jane Furse ](+27832195400*)[ 🏥 Women's Abortion Clinic i...Abortion Pill Prices Jane Furse ](+27832195400*)[ 🏥 Women's Abortion Clinic i...
Abortion Pill Prices Jane Furse ](+27832195400*)[ 🏥 Women's Abortion Clinic i...
 
Spring into AI presented by Dan Vega 5/14
Spring into AI presented by Dan Vega 5/14Spring into AI presented by Dan Vega 5/14
Spring into AI presented by Dan Vega 5/14
 
The mythical technical debt. (Brooke, please, forgive me)
The mythical technical debt. (Brooke, please, forgive me)The mythical technical debt. (Brooke, please, forgive me)
The mythical technical debt. (Brooke, please, forgive me)
 
Evolving Data Governance for the Real-time Streaming and AI Era
Evolving Data Governance for the Real-time Streaming and AI EraEvolving Data Governance for the Real-time Streaming and AI Era
Evolving Data Governance for the Real-time Streaming and AI Era
 
Abortion Pills For Sale WhatsApp[[+27737758557]] In Birch Acres, Abortion Pil...
Abortion Pills For Sale WhatsApp[[+27737758557]] In Birch Acres, Abortion Pil...Abortion Pills For Sale WhatsApp[[+27737758557]] In Birch Acres, Abortion Pil...
Abortion Pills For Sale WhatsApp[[+27737758557]] In Birch Acres, Abortion Pil...
 
UNI DI NAPOLI FEDERICO II - Il ruolo dei grafi nell'AI Conversazionale Ibrida
UNI DI NAPOLI FEDERICO II - Il ruolo dei grafi nell'AI Conversazionale IbridaUNI DI NAPOLI FEDERICO II - Il ruolo dei grafi nell'AI Conversazionale Ibrida
UNI DI NAPOLI FEDERICO II - Il ruolo dei grafi nell'AI Conversazionale Ibrida
 
Workshop: Enabling GenAI Breakthroughs with Knowledge Graphs - GraphSummit Milan
Workshop: Enabling GenAI Breakthroughs with Knowledge Graphs - GraphSummit MilanWorkshop: Enabling GenAI Breakthroughs with Knowledge Graphs - GraphSummit Milan
Workshop: Enabling GenAI Breakthroughs with Knowledge Graphs - GraphSummit Milan
 
Modern binary build systems - PyCon 2024
Modern binary build systems - PyCon 2024Modern binary build systems - PyCon 2024
Modern binary build systems - PyCon 2024
 
Effective Strategies for Wix's Scaling challenges - GeeCon
Effective Strategies for Wix's Scaling challenges - GeeConEffective Strategies for Wix's Scaling challenges - GeeCon
Effective Strategies for Wix's Scaling challenges - GeeCon
 
Abortion Clinic In Pretoria ](+27832195400*)[ 🏥 Safe Abortion Pills in Pretor...
Abortion Clinic In Pretoria ](+27832195400*)[ 🏥 Safe Abortion Pills in Pretor...Abortion Clinic In Pretoria ](+27832195400*)[ 🏥 Safe Abortion Pills in Pretor...
Abortion Clinic In Pretoria ](+27832195400*)[ 🏥 Safe Abortion Pills in Pretor...
 
Anypoint Code Builder - Munich MuleSoft Meetup - 16th May 2024
Anypoint Code Builder - Munich MuleSoft Meetup - 16th May 2024Anypoint Code Builder - Munich MuleSoft Meetup - 16th May 2024
Anypoint Code Builder - Munich MuleSoft Meetup - 16th May 2024
 
Workshop - Architecting Innovative Graph Applications- GraphSummit Milan
Workshop -  Architecting Innovative Graph Applications- GraphSummit MilanWorkshop -  Architecting Innovative Graph Applications- GraphSummit Milan
Workshop - Architecting Innovative Graph Applications- GraphSummit Milan
 

10. copy and move

  • 1.
  • 3. 01. void test(complex z1) 02. { 03. complex z2(z1); // Copy initialization 04. complex z3; 05. z3 = z2; // Copy assignment 06. // ... 07. }
  • 4. 01. void bad_copy(Vector v1) 02. { 03. Vector v2 = v1; // Copy v1's representation into v2 04. v1[0] = 2; // v2[0] is now also 2! 05. v2[1] = 3; // v1[1] is now also 3! 06. }
  • 5. 01. class Vector { 02. private: 03. // elem points to an array of sz doubles 04. double* elem; 05. int sz; 06. public: 07. Vector(int s); // Constructor 08. ~Vector() { delete[] elem; } // Destructor 09. 10. Vector(const Vector& a); // Copy constructor 11. Vector& operator=(const Vector& a); // Copy assignment 12. 13. double& operator[](int i); 14. const double& operator[](int i) const; 15. int size() const; 16. };
  • 6. 01. Vector::Vector(const Vector& a) // Copy constructor 02. : elem(new double[sz]) // Allocate space for elements 03. , sz(a.sz) 04. { 05. for (int i = 0; i != sz; ++i) // Copy elements 06. elem[i] = a.elem[i]; 07. }
  • 7. 01. // Copy assignment 02. Vector& vector::operator=(const Vector& a) 03. { 04. double* p = new double[a.sz]; 05. for (int i = 0; i != a.sz; ++i) 06. p[i] = a.elem[i]; 07. delete[] elem; 08. elem = p; 09. sz = a.sz; 10. return *this; 11. }
  • 8. 01. Vector operator+(const Vector& a, const Vector& b) 02. { 03. if (a.size() != b.size()) 04. throw Vector_size_mismatch(); 05. Vector res(a.size()); 06. for (int i = 0; i != a.size(); ++i) 07. res[i] = a[i] + b[i]; 08. return res; 09. } 01. void f(const Vector& x, const Vector& y, const Vector& z) 02. { 03. Vector r; 04. // ... 05. r = x + y + z; 06. // ... 07. }
  • 9. 01. class Vector { 02. // ... 03. Vector(const Vector& a); // Copy constructor 04. Vector& operator=(const Vector& a); // Copy assignment 05. 06. Vector(Vector&& a); // Move constructor 07. Vector& operator=(Vector&& a); // Move assignment 08. }; 09. 10. Vector::Vector(Vector&& a) 11. : elem(a.elem) // "grab the elements" form a 12. , sz(a.sz) 13. { 14. a.elem = nullptr; // Now a has no elements 15. a.sz = 0; 16. }
  • 10. 01. Vector f() 02. { 03. Vector x(1000); 04. Vector y(1000); 05. Vector z(1000); 06. // ... 07. z = x; // We get a copy 08. y = std::move(x); // We get a move 09. // ... 10. return z; // We get a move 11. }
  • 11. 01. class Shape { 02. public: 03. // No copy operations 04. Shape(const Shape&) = delete; 05. Shape& operator=(const Shape&) = delete; 06. 07. // No move operations 08. Shape(Shape&&) = delete; 09. Shape& operator=(Shape&&) = delete; 10. 11. ~Shape(); 12. // ... 13. };

Editor's Notes

  1. توی این ویدیو در مورد کپی و move صحبت خواهیم کرد و مفهوم اونا رو با مثال شرح خواهم داد و در نهایت روشی که در C++11 برای غیر فعال کردن اونا وجود داره هم اشاره میکنم.
  2. به طور پیش فرض تمام Objectها رو چه از نوع built-in باشن چه از نوع user-defined باشن میشه کپی کرد. معنی کپی اینه که به صورت Member wise کپی صورت می گیره. معنی member wise اینه که وقتی یک Object رو برابر یک Object دیگه از همون نوع قرار میدیم اعضای اولی برابر دومی قرار میگیره، مثلا تمام اعضای z3 نظیر به نظیر برابر اعضای z2 قرار می گیرند و مقدار ها شون با هم برابر میشه. الان z2 وz3 برابر هم هستند و یک مقدار درونشون قرار داره. زمانی که یک کلاس طراحی و پیاده سازی می کنیم باید به این نکته توجه کنیم که چطور اون کلاس کپی میشه. معمولا member wise کپی کردن جواب میده و اکثر مواقع درست کار میکنه. ولی موقعیت های پیچیده تری هم ممکنه پیش بیاد که درست جواب نده و نتیجه غلط بده مخصوصا برای Abstract type ها و Containerها.
  3. زمانی که ما کلاسی داریم که از طریق pointer به یکسری اطلاعات دیگه دسترسی داریم؛ member wise کپی کردن نتایج خیلی بد و فاجعه باری خواهد داشت. برای مثال فرض کنید که ما کلاس vector رو به صورتی نوشته باشیم که member wise کپی کنه. در اون صورت با این کد دوتا vector های v1 و v2 هر دوتاشون به یک جا اشاره خواهند کرد. به صورت شماتیک در شکل می بینید. فرض کنید v1 چهار تا المان توش باشه. در این صورت می بینید که با member wise کپی کردن pointerهای هر دوتاشون به یک جا اشاره می کنن و هر کدوم رو که تغییر بدیم روی اون یکی هم اعمال میشه.
  4. پس در مورد vector ما نیاز داریم که یک راه بهتری برای کپی کردن پیدا کنیم. این کار رو با copy constructor و copy assignment انجام میدیم. در copy constructor و copy assignment آرگمان ورودی از نوع const Vector& هستند.
  5. یه پیاده سازی خوب برای کپی کردن به این صورته که در copy constructor اول فضای مورد نیاز برای ذخیره کردن المان های مورد نیاز رو allocate میکنیم و بعد هر المان رو داخل فضای جدید که allocate کردیم کپی می کنیم. در شکل می بینید که حالا با کپی کردن؛ دو تا vector به دو تا فضای مستقل از هم اشاره می کنند و دیگه تغییرات هر کدوم روی اون یکی تاثیری نخواهد داشت.
  6. به همین صورت ما برای assignment هم به copy assignment نیاز داریم. اول با new یه فضای جدید Allocate می کنیم و بعد در اون فضای جدید المانهای مورد نظر رو کپی می کنیم. بعد حافظه ی مربوط به المانهای قدیمی رو با استفاده از delete آزاد می کنیم. و آدرس و size جدید رو ذخیره می کنیم. This در member functionها یک معنای خاصی داره و به این معنی هست که یک Pointer به خود اون objectیی هست که داره این متد درون اون قرارداره و داره اون رو اجرا می کنه و کامپایلر بجای this آدرس اون Object رو قرار میده. در آخر هم به عنوان خروجی اپراتور خود این object رو بر گردوندیم.
  7. ما تونستیم با copy constructor و copy assignment نحوه ی کپی شدن رو کنترل کنیم. ولی برای Objectهای بزرگ و containerهای بزرگ عملیات کپی خیلی هزینه داره. مثلا فرض کنید که ما یک container داریم که حجمش 1 گیگا بایت باشه و اگه بخوایم اون رو کپی کنیم سیستم خیلی کند میشه و حتی ممکنه هنگ کنه و مجبور بشیم سیستم رو ریست کنیم. توی این مثال یه اپراتور + نوشتیم که 2 تا وکتور رو با هم جمع می کنه و حاصل جمع نظیر به نظیر اعضای اون ها رو توی یک وکتور دیگه به نام res می ریزه و اون رو به عنوان حاصل به اون جایی که تابع رو صدا کرده بر می گردونه. توی این مثال حداقل 2 بار عملیات کپی صورت خواهد گرفت که بسیار پر هزینه هست. برای هر کدوم از +ها یک بار حاصل جمع حساب میشه و کپی صورت می گیره. بیاید فرض کنیم که وکتور ها بزگ باشن و توی هر وکتور ده هزار تا double داریم. نکته اینجاست که ما نمی خوایم که هر بار 10هزارتا double رو کپی کنیم بلکه می خوایم حاصل جمع رو یک جا نگه داریم و روی اون عملیات رو انجام بدیم. پس بجای اینکه ما هر بار وکتور رو کپی کنیم اون رو move می کنیم.
  8. برای move کردن ما باید از move constructor استفاده کنیم تا به کامپایلر بگیم که بجای اینکه عمل کپی رو انجام بده برای ما move انجام بده و حاصل عملیات یک تابع رو به خارج از تابع بفرسته. این 2 تا && به معنی rvalue reference هست. rvalue در مقابل lvalue ساخته شده. Lvalue به معنی چیزهایی هست که سمت چپ یک عبارت محاسباتی یا به عبارتی سمت چپ علامت مساوی قرار می گیرند. اما rvalue چیزی هست که سمت راست قرار میگیره و شما نمی تونید چیزی رو بهش Assign کنید. به عنوان مثال یک integer یا عددی که به عنوان return type یک تابع بر می گردونید یک rvalue هست. و rvalue reference هم یک reference هست به یه چیزی که کسی نمیتونه بهش چیزی رو assign کنه. برای مثال وکتور res توی اسلاید قبلی یک rvalue reference هست. Move constructor پارامتر ورودی رو به عنوان const نمی گیره و فرض بر اینه که در move constructor مقادیر آرگمان ورودی توسط کانستراکتور Remove خواهند شد. از move constructor زمانی استفاده میشه که از یک rvalue در سمت راست مساوی برای initializeکردن استفاده بشه.
  9. زمانی که تشخیص میدیم که یک مقداری دیگه استفاده نمی شه ولی مطمئن نیستیم که کامپایلر این موضوع رو بفهمه می تونیم از std::move استفاده کنه. تابع move از کتابخونه استاندارد یک rvalue از آرگمان ورودیش بر می گردونه. در این مثال درست قبل از اینکه از تابع return کنیم وضعیت objectها به این صورت خواهد بود. وقتی return صورت بگیره مقدار z به بیرون از تابع move خواهد شد. و x هم هیچ مقداری درونش نخواهد بود.
  10. استفاده از copy و Move به صورت default در hierarchy کلاسها می تونه نتایج مخربی داشته باشه. زمانی که فقط یه pointer از base داشته باشیم نمی دونیم که کلاس derived چه memberهایی داره که کپی شون کنیم. وقتی که ندونیم چطور باید یک object رو کپی کنیم بهتره که این قابلیت های default رو غیر فعال کنیم. در c++11 با استفاده از delete= می تونیم به این صورت این قابلیت های default رو غیر فعال کنیم. حالا اگه کاری کنیم که Object از نوع Shape بخواد کپی بشه کامپایلر خطا میده و جلوی انجام شدن اون کار رو میگیره.
  11. در این ویدیو در مورد Copy و Move صحبت کردیم و اینکه چطور container ها رو باید درست کپی کرد و با استفاده از Move هم چطور می شه کارایی برنامه هایی که می نویسیم زمانی که کپی کردن پر هزینه باشه رو بالا تر ببریم. در آخر هم گفتیم که چطور می شه عملیات های copy و move رو غیر فعال کرد.