SlideShare a Scribd company logo
1 of 13
Arindam Mukherjee 
Pune C++ and Boost Meetup 
C++11 MOVE SEMANTICS
Copying objects is bad 
 Extra memory, extra CPU cycles to copy. 
 May allocate heap memory, file descriptors, 
etc. 
 May fail.
Temporaries 
 Objects not bound to a variable name 
 Lifetime limited to the statement that 
creates them 
 Examples: 
std::string s1, s2, s3; 
std::string getName(); // prototype 
std::string s4 = s1 + s2 + s3; // may copy 
std::string s5 = getName(); // may copy
Return Value Optimization 
 Copy elision: optimize copies, even when 
they have side effects 
 RVO: Elide copying of a returned temporary. 
std::string getName() { return "foo"; } 
std::string name = getName(); 
 Named RVO: Elide copying of a named 
variable when returned from a function. 
std::string getName() { 
std::string s = "foo"; 
return s; }
RVO: no guarantees 
 May not take effect in: 
- Debug builds. 
- Many but the most simple cases: 
- Returning different named objects from 
different return statements disables NRVO. 
- NRVO does not mix with RVO.
Move, not copy 
 Do a shallow copy to the destination 
 Reset the source and stop using it 
 Useful when: 
- You anyway can’t use the source later: 
std::string s = s1 + s2; 
// s1 + s2 is a temporary 
- You know you won’t use the source later. 
- Copying is expensive and can fail.
l-value, r-value 
 l-values: expressions with durable address. 
May not be ok to move from. 
int x = 5;foo(x); 
char arr[16];arr[5] = 20; 
 r-values: expressions without a durable 
address – temporaries – always ok to move 
from. 
const string& s = string("Foo"), s2, s3; 
setName(getName()); 
s3 = s + s2;
Overload on l- && r-values 
 foo(string& s); // foo(s); 
foo(const string& s); // foo(s1 + s2); 
 Does not work because to move from, we 
need a mutable reference. 
 New class of mutable references – r-value 
references: 
foo(string& s); // foo(s); 
foo(string&& s); // foo(s1 + 2); 
// foo(getName())
Move: Overloading copy 
 Copy suite: 
string(const string& that); 
string& operator=(const string& rhs); 
 Move suite: 
string(string&& that) noexcept; 
string& operator=(string&& rhs) noexcept;
Implementing move 
 X&& var only says it is ok to move from var. 
 foo(X&& var) says foo may move from var. 
 Implementer of foo still has to code the 
actual move. 
 Define a nothrow swap function that 
exchanges pointers and primitive types or 
delegates to other swaps. Swap source with 
target. 
 Make sure source is destructible after swap.
Return by value 
 Return by value prefers move over copy. 
std::string getName() { 
std::string s1; 
if (s1.size() > 0) {return s1;} //move 
else {return string("default");} // rvo 
} 
std::string s1 = getName(); // rvo or move
Moving l-values 
 You know you won’t use the source object 
after this, but compiler doesn’t – so tell it. 
foo(string& s); // 1 
foo(string&& s); // 2 
std::string s("Hello"); 
foo(s); // calls 1 
foo(std::move(s)); // calls 2 
 std::move casts the l-value expression to an r-value 
expression.
Thank you! 
 Q & A 
 Thomas Becker’s C++ Rvalue references 
explained: http://bit.ly/1ACRnAe

More Related Content

What's hot

Variadic functions
Variadic functionsVariadic functions
Variadic functionsramyaranjith
 
A698111855 22750 26_2018_finite
A698111855 22750 26_2018_finiteA698111855 22750 26_2018_finite
A698111855 22750 26_2018_finiteMohd Arif Ansari
 
20190221 fourier series
20190221 fourier series20190221 fourier series
20190221 fourier seriesgrantkobe
 
Dependent voltage source (vsource)
Dependent voltage source (vsource)Dependent voltage source (vsource)
Dependent voltage source (vsource)Tsuyoshi Horigome
 
Hot С++: Universal References And Perfect Forwarding
Hot С++: Universal References And Perfect ForwardingHot С++: Universal References And Perfect Forwarding
Hot С++: Universal References And Perfect ForwardingAndrey Upadyshev
 
Promise of an API
Promise of an APIPromise of an API
Promise of an APIMaxim Zaks
 
[C++ Korea] Effective Modern C++ Study item 34 36
[C++ Korea] Effective Modern C++ Study item 34 36[C++ Korea] Effective Modern C++ Study item 34 36
[C++ Korea] Effective Modern C++ Study item 34 36Seok-joon Yun
 
When RV Meets CEP (RV 2016 Tutorial)
When RV Meets CEP (RV 2016 Tutorial)When RV Meets CEP (RV 2016 Tutorial)
When RV Meets CEP (RV 2016 Tutorial)Sylvain Hallé
 
BeepBeep 3: A declarative event stream query engine (EDOC 2015)
BeepBeep 3: A declarative event stream query engine (EDOC 2015)BeepBeep 3: A declarative event stream query engine (EDOC 2015)
BeepBeep 3: A declarative event stream query engine (EDOC 2015)Sylvain Hallé
 
Activity Recognition Through Complex Event Processing: First Findings
Activity Recognition Through Complex Event Processing: First Findings Activity Recognition Through Complex Event Processing: First Findings
Activity Recognition Through Complex Event Processing: First Findings Sylvain Hallé
 
The Little Register Allocator
The Little Register AllocatorThe Little Register Allocator
The Little Register AllocatorIan Wang
 
scala-gopher: async implementation of CSP for scala
scala-gopher:  async implementation of CSP  for  scalascala-gopher:  async implementation of CSP  for  scala
scala-gopher: async implementation of CSP for scalaRuslan Shevchenko
 

What's hot (20)

Variadic functions
Variadic functionsVariadic functions
Variadic functions
 
R/C++ talk at earl 2014
R/C++ talk at earl 2014R/C++ talk at earl 2014
R/C++ talk at earl 2014
 
C++11
C++11C++11
C++11
 
Rcpp11 useR2014
Rcpp11 useR2014Rcpp11 useR2014
Rcpp11 useR2014
 
Reconstruction
ReconstructionReconstruction
Reconstruction
 
A698111855 22750 26_2018_finite
A698111855 22750 26_2018_finiteA698111855 22750 26_2018_finite
A698111855 22750 26_2018_finite
 
C++11 & C++14
C++11 & C++14C++11 & C++14
C++11 & C++14
 
20190221 fourier series
20190221 fourier series20190221 fourier series
20190221 fourier series
 
Dependent voltage source (vsource)
Dependent voltage source (vsource)Dependent voltage source (vsource)
Dependent voltage source (vsource)
 
Hot С++: Universal References And Perfect Forwarding
Hot С++: Universal References And Perfect ForwardingHot С++: Universal References And Perfect Forwarding
Hot С++: Universal References And Perfect Forwarding
 
Promise of an API
Promise of an APIPromise of an API
Promise of an API
 
[C++ Korea] Effective Modern C++ Study item 34 36
[C++ Korea] Effective Modern C++ Study item 34 36[C++ Korea] Effective Modern C++ Study item 34 36
[C++ Korea] Effective Modern C++ Study item 34 36
 
When RV Meets CEP (RV 2016 Tutorial)
When RV Meets CEP (RV 2016 Tutorial)When RV Meets CEP (RV 2016 Tutorial)
When RV Meets CEP (RV 2016 Tutorial)
 
Rcpp11 genentech
Rcpp11 genentechRcpp11 genentech
Rcpp11 genentech
 
BeepBeep 3: A declarative event stream query engine (EDOC 2015)
BeepBeep 3: A declarative event stream query engine (EDOC 2015)BeepBeep 3: A declarative event stream query engine (EDOC 2015)
BeepBeep 3: A declarative event stream query engine (EDOC 2015)
 
Activity Recognition Through Complex Event Processing: First Findings
Activity Recognition Through Complex Event Processing: First Findings Activity Recognition Through Complex Event Processing: First Findings
Activity Recognition Through Complex Event Processing: First Findings
 
Loops (1)
Loops (1)Loops (1)
Loops (1)
 
The Little Register Allocator
The Little Register AllocatorThe Little Register Allocator
The Little Register Allocator
 
scala-gopher: async implementation of CSP for scala
scala-gopher:  async implementation of CSP  for  scalascala-gopher:  async implementation of CSP  for  scala
scala-gopher: async implementation of CSP for scala
 
Semaphore
SemaphoreSemaphore
Semaphore
 

Similar to C++11 move semantics

C++ Strings.ppt
C++ Strings.pptC++ Strings.ppt
C++ Strings.pptDilanAlmsa
 
C++11: Rvalue References, Move Semantics, Perfect Forwarding
C++11: Rvalue References, Move Semantics, Perfect ForwardingC++11: Rvalue References, Move Semantics, Perfect Forwarding
C++11: Rvalue References, Move Semantics, Perfect ForwardingFrancesco Casalegno
 
Functions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrupFunctions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrupSyedHaroonShah4
 
46630497 fun-pointer-1
46630497 fun-pointer-146630497 fun-pointer-1
46630497 fun-pointer-1AmIt Prasad
 
Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)David Atchley
 
The C++ rvalue lifetime disaster. Arno Schödl ➠ CoreHard Autumn 2019
The C++ rvalue lifetime disaster. Arno Schödl ➠ CoreHard Autumn 2019The C++ rvalue lifetime disaster. Arno Schödl ➠ CoreHard Autumn 2019
The C++ rvalue lifetime disaster. Arno Schödl ➠ CoreHard Autumn 2019corehard_by
 
Hot C++: Rvalue References And Move Semantics
Hot C++: Rvalue References And Move SemanticsHot C++: Rvalue References And Move Semantics
Hot C++: Rvalue References And Move SemanticsAndrey Upadyshev
 
The Swift Compiler and Standard Library
The Swift Compiler and Standard LibraryThe Swift Compiler and Standard Library
The Swift Compiler and Standard LibrarySantosh Rajan
 
Clojure concurrency
Clojure concurrencyClojure concurrency
Clojure concurrencyAlex Navis
 
A Brief Intro to Scala
A Brief Intro to ScalaA Brief Intro to Scala
A Brief Intro to ScalaTim Underwood
 
A Recovering Java Developer Learns to Go
A Recovering Java Developer Learns to GoA Recovering Java Developer Learns to Go
A Recovering Java Developer Learns to GoMatt Stine
 
Hot C++: New Style of Arguments Passing
Hot C++: New Style of Arguments PassingHot C++: New Style of Arguments Passing
Hot C++: New Style of Arguments PassingAndrey Upadyshev
 
Ti1220 Lecture 2: Names, Bindings, and Scopes
Ti1220 Lecture 2: Names, Bindings, and ScopesTi1220 Lecture 2: Names, Bindings, and Scopes
Ti1220 Lecture 2: Names, Bindings, and ScopesEelco Visser
 
Basics of Javascript
Basics of JavascriptBasics of Javascript
Basics of JavascriptUniverse41
 
ES6 General Introduction
ES6 General IntroductionES6 General Introduction
ES6 General IntroductionThomas Johnston
 

Similar to C++11 move semantics (20)

The_Borrow_Checker.pdf
The_Borrow_Checker.pdfThe_Borrow_Checker.pdf
The_Borrow_Checker.pdf
 
C++ Strings.ppt
C++ Strings.pptC++ Strings.ppt
C++ Strings.ppt
 
C++11: Rvalue References, Move Semantics, Perfect Forwarding
C++11: Rvalue References, Move Semantics, Perfect ForwardingC++11: Rvalue References, Move Semantics, Perfect Forwarding
C++11: Rvalue References, Move Semantics, Perfect Forwarding
 
Functions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrupFunctions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrup
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
 
46630497 fun-pointer-1
46630497 fun-pointer-146630497 fun-pointer-1
46630497 fun-pointer-1
 
Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)
 
The C++ rvalue lifetime disaster. Arno Schödl ➠ CoreHard Autumn 2019
The C++ rvalue lifetime disaster. Arno Schödl ➠ CoreHard Autumn 2019The C++ rvalue lifetime disaster. Arno Schödl ➠ CoreHard Autumn 2019
The C++ rvalue lifetime disaster. Arno Schödl ➠ CoreHard Autumn 2019
 
Shell scripting
Shell scriptingShell scripting
Shell scripting
 
Hot C++: Rvalue References And Move Semantics
Hot C++: Rvalue References And Move SemanticsHot C++: Rvalue References And Move Semantics
Hot C++: Rvalue References And Move Semantics
 
The Swift Compiler and Standard Library
The Swift Compiler and Standard LibraryThe Swift Compiler and Standard Library
The Swift Compiler and Standard Library
 
Clojure concurrency
Clojure concurrencyClojure concurrency
Clojure concurrency
 
A Brief Intro to Scala
A Brief Intro to ScalaA Brief Intro to Scala
A Brief Intro to Scala
 
A Recovering Java Developer Learns to Go
A Recovering Java Developer Learns to GoA Recovering Java Developer Learns to Go
A Recovering Java Developer Learns to Go
 
Hot C++: New Style of Arguments Passing
Hot C++: New Style of Arguments PassingHot C++: New Style of Arguments Passing
Hot C++: New Style of Arguments Passing
 
Ti1220 Lecture 2: Names, Bindings, and Scopes
Ti1220 Lecture 2: Names, Bindings, and ScopesTi1220 Lecture 2: Names, Bindings, and Scopes
Ti1220 Lecture 2: Names, Bindings, and Scopes
 
Basics of Javascript
Basics of JavascriptBasics of Javascript
Basics of Javascript
 
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
 
ES6 General Introduction
ES6 General IntroductionES6 General Introduction
ES6 General Introduction
 
Rustlabs Quick Start
Rustlabs Quick StartRustlabs Quick Start
Rustlabs Quick Start
 

Recently uploaded

Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 

Recently uploaded (20)

Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 

C++11 move semantics

  • 1. Arindam Mukherjee Pune C++ and Boost Meetup C++11 MOVE SEMANTICS
  • 2. Copying objects is bad  Extra memory, extra CPU cycles to copy.  May allocate heap memory, file descriptors, etc.  May fail.
  • 3. Temporaries  Objects not bound to a variable name  Lifetime limited to the statement that creates them  Examples: std::string s1, s2, s3; std::string getName(); // prototype std::string s4 = s1 + s2 + s3; // may copy std::string s5 = getName(); // may copy
  • 4. Return Value Optimization  Copy elision: optimize copies, even when they have side effects  RVO: Elide copying of a returned temporary. std::string getName() { return "foo"; } std::string name = getName();  Named RVO: Elide copying of a named variable when returned from a function. std::string getName() { std::string s = "foo"; return s; }
  • 5. RVO: no guarantees  May not take effect in: - Debug builds. - Many but the most simple cases: - Returning different named objects from different return statements disables NRVO. - NRVO does not mix with RVO.
  • 6. Move, not copy  Do a shallow copy to the destination  Reset the source and stop using it  Useful when: - You anyway can’t use the source later: std::string s = s1 + s2; // s1 + s2 is a temporary - You know you won’t use the source later. - Copying is expensive and can fail.
  • 7. l-value, r-value  l-values: expressions with durable address. May not be ok to move from. int x = 5;foo(x); char arr[16];arr[5] = 20;  r-values: expressions without a durable address – temporaries – always ok to move from. const string& s = string("Foo"), s2, s3; setName(getName()); s3 = s + s2;
  • 8. Overload on l- && r-values  foo(string& s); // foo(s); foo(const string& s); // foo(s1 + s2);  Does not work because to move from, we need a mutable reference.  New class of mutable references – r-value references: foo(string& s); // foo(s); foo(string&& s); // foo(s1 + 2); // foo(getName())
  • 9. Move: Overloading copy  Copy suite: string(const string& that); string& operator=(const string& rhs);  Move suite: string(string&& that) noexcept; string& operator=(string&& rhs) noexcept;
  • 10. Implementing move  X&& var only says it is ok to move from var.  foo(X&& var) says foo may move from var.  Implementer of foo still has to code the actual move.  Define a nothrow swap function that exchanges pointers and primitive types or delegates to other swaps. Swap source with target.  Make sure source is destructible after swap.
  • 11. Return by value  Return by value prefers move over copy. std::string getName() { std::string s1; if (s1.size() > 0) {return s1;} //move else {return string("default");} // rvo } std::string s1 = getName(); // rvo or move
  • 12. Moving l-values  You know you won’t use the source object after this, but compiler doesn’t – so tell it. foo(string& s); // 1 foo(string&& s); // 2 std::string s("Hello"); foo(s); // calls 1 foo(std::move(s)); // calls 2  std::move casts the l-value expression to an r-value expression.
  • 13. Thank you!  Q & A  Thomas Becker’s C++ Rvalue references explained: http://bit.ly/1ACRnAe