SlideShare a Scribd company logo
1 of 24
Download to read offline
Move semantics







Introduction: copying temporaries
pitfall
Moving constructors
Perfect forwarding
Extending horizons: tips & tricks
Q&A


Find an error and propose a fix:

vector<string>& getNames() {
vector<string> names;
names.push_back("Ivan");
names.push_back("Artem");
return names;
}


Possible solutions:

1

void getNames(vector<string>& names) {
names.push_back("Ivan");
names.push_back("Artem");
}

vector<string> names;
getNames(names);

auto_ptr<vector<string> > names(
getNames());

2

auto_ptr<vector<string> > getNames() {
auto_ptr<vector<string> > names(
new vector<string>);
names->push_back("Ivan");
names->push_back("Artem");
return names;
}

vector<string> const& names =
getNames();

3

vector<string> getNames() {
vector<string> names;
names.push_back("Ivan");
names.push_back("Artem");
return names;
}


Compiler:
Return Value Optimization (RVO);
Named Return Value Optimization (NRVO).

•
•


Techniques:
Copy-on-write (COW);
“Move Constructors”:

•
•


Simulate temporary objects and treat them
differently.


Language:
•
•

Recognize temporary objects;
Treat temporary objects differently.
expression

glvalue

rvalue

(“generalized”
lvalue)

lvalue

xvalue
(“eXpiring”
value)

prvalue
(“pure” rvalue)
lvalue



•


•

identifies a non-temporary object.

prvalue

“pure rvalue” - identifies a temporary object or is a
value not associated with any object.

xvalue



•

either temporary object or non-temporary object at
the end of its scope.

glvalue



•


•

either lvalue or xvalue.

rvalue

either prvalue or xvalue.
class Buffer {
char* _data;
size_t _size;
// ...
// copy the content from lvalue
Buffer(Buffer const& lvalue)
: _data(nullptr), _size(0)
{
// perform deep copy ...
}
// take the internals from rvalue
Buffer(Buffer&& rvalue)
: _data(nullptr), _size(0)
{
swap(_size, rvalue._size);
swap(_data, rvalue._data);
// it is vital to keep rvalue
// in a consistent state
}
// ...

Buffer getData() { /*...*/ }
// ...
Buffer someData;
// ... initialize someData
Buffer someDataCopy(someData);
// make a copy
Buffer anotherData(getData());
// move temporary
class Configuration {
// ...
Configuration(
Configuration const&);
Configuration const& operator=(
Configuration const& );
Configuration(Configuration&& );
Configuration const& operator=(
Configuration&& );
// ...
};
class ConfigurationStorage;
class ConfigurationManger {
// ...
Configuration _current;
// ...
bool reload(ConfigurationStorage& );
// ...
};

bool
ConfigurationManager::reload(
ConfigurationStorage& source
) {
Configuration candidate =
source.retrieve();
// OK, call move ctor
if (!isValid(candidate)) {
return false;
}
_current = candidate;
// BAD, copy lvalue to lvalue
_current = move(candidate);
// OK, use move assignment
return true;
}
Does not really move anything;
 Does cast a reference to object to
xvalue:


template<typename _T>
typename remove_reference<_T>::type&&
move(_T&& t) {
return static_cast<typename remove_reference<_T>::type&&>(t);
}



Does not produce code for run-time.






Move is an optimization for copy.
Copy of rvalue objects may become
move.
Explicit move for objects without move
support becomes copy.
Explicit move objects of built-in types
always becomes copy.
Compiler does generate move
constructor/assignment operator when:



•
•
•

there is no user-defined copy or move operations (including
default);
there is no user-defined destructor (including default);
all non-static members and base classes are movable.



Implicit move constructor/assignment operator
does perform member-wise moving.



Force-generated move operators does perform
member-wise moving:
•

dangerous when dealing with raw resources (memory, handles,
etc.).
class Configuration {
// have copy & move operations implemented
// ...
};
class ConfigurationManger {
// ...
Configuration _current;
// ...
ConfigurationManager(Configuration const& defaultConfig)
: _current(defaultConfig) // call copy ctor
{ }
ConfigurationManager(Configuration&& defaultConfig)
// : _current(defaultConfig) // BAD, call copy ctor
: _current(move(defaultConfig)) // OK, call move ctor
{ }
// ...
};
class Configuration {
// have copy & move operations implemented
// ...
};
class ConfigurationManger {
// ...
Configuration _current;
// ...
template <class _ConfigurationRef>
explicit ConfigurationManager(_ConfigurationRef&& defaultConfig)
: _current(forward<_ConfigurationRef>(defaultConfig))
// OK, deal with either rvalue or lvalue
{ }
// ...
};
 Normally

C++ does not allow reference to
reference types.
 Template types deduction often does
produce such types.
 There are rules for deduct a final type then:
•
•
•
•

T& &
 T&
T& &&  T&
T&& &  T&
T&& &&  T&&
Just a cast as well;
 Applicable only for function templates;
 Preserves arguments
lvaluesness/rvaluesness/constness/etc.


template<typename _T>
_T&&
forward(typename remove_reference<_T>::type& t) {
return static_cast<_T&&>(t);
}

template<typename _T>
_T&&
forward(typename remove_reference<_T>::type&& t) {
return static_cast<_T&&>(t);
}
class ConfigurationManger {
template <class _ConfigurationType>
ConfigurationManager(_ConfigurationType&& defaultConfig)
: _current(forward<_ConfigurationType>(defaultConfig))
{}
// ...
};
// ...
Configuration defaultConfig;
ConfigurationManager configMan(defaultConfig);
// _ConfigurationType => Configuration&
// decltype(defaultConfig) => Configuration& && => Configuration&
// forward => Configuration& && forward<Configuration&>(Configuration& )
//
=> Configuration& forward<Configuration&>(Configuration& )
ConfigurationManager configMan(move(defaultConfig));
// _ConfigurationType => Configuration
// decltype(defaultConfig) => Configuration&&
// forward => Configuration&& forward<Configuration>(Configuration&& )


Passing parameters to functions:

class ConfigurationStorage {
std::string _path;
// ...
template <class _String>
bool open(_String&& path) {
_path = forward<_String>(path);
// ...
}
};
// ...
string path("somewhere_near_by");
ConfigurationStorage storage;
storage.open(path);
// OK, pass as string const&
storage.open(move(path));
// OK, pass as string&&
storage.open("far_far_away"); // OK, pass as char const*


Passing parameters by value:

class ConfigurationManger {
Configuration _current;
// ...
bool setup(
Configuration const& newConfig) {
_current = newConfig; // make a copy
}
bool setup(
Configuration&& newConfig) {
_current = move(newConfig);
// simply take it
}
};
Configuration config;
configManager.setup(config);
// pass by const&
configManager.setup(move(config));
// pass by &&

class ConfigurationManger {
Configuration _current;
// ...
bool setup(
Configuration newConfig) {
// ...
_current = move(newConfig);
// could just take it
}
};

Configuration config;
configManager.setup(config);
// make copy ahead
configManager.setup(move(config));
// use move ctor


Return results:

vector<string> getNamesBest() {
vector<string> names;
// ...
return names; // OK, compiler choice for either of move ctor or RVO
}
vector<string> getNamesGood() {
vector<string> names;
// ...
return move(names); // OK, explicit call move ctor
}
vector<string>&& getNamesBad() {
vector<string> names;
// ...
return move(names); // BAD, return a reference to a local object
}


Extending object life-time:

vector<string> getNames() {
vector<string> names;
// ...
return names;
}
// ...
vector<string> const& names = getNames(); //
vector<string>&& names = getNames();
//
vector<string> names = getNames();
//
vector<string>& names = getNames();
//
vector<string>&& names = move(getNames());//

OK, both C++03/C++11
OK, C++11: extends life-time
OK, C++11: move construction
BAD, dangling reference here
BAD, dangling reference here
The hardest work for move semantic
support usually performed by the compiler
and the Standard Library.
 There is still a lot of space for apply move
semantic explicitly for performance critical
parts of the application:


• It is up to developer to ensure the code correctness

when the move semantic used explicitly.
• The best way to add move semantic support to own
class is using pImpl idiom.
C++ 11 usage experience

More Related Content

What's hot

HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
Dmitry Soshnikov
 
Rust-lang
Rust-langRust-lang
Обзор фреймворка Twisted
Обзор фреймворка TwistedОбзор фреймворка Twisted
Обзор фреймворка Twisted
Maxim Kulsha
 

What's hot (20)

Spockを使おう!
Spockを使おう!Spockを使おう!
Spockを使おう!
 
Swift 3 Programming for iOS : subscript init
Swift 3 Programming for iOS : subscript initSwift 3 Programming for iOS : subscript init
Swift 3 Programming for iOS : subscript init
 
Scientific Computing with Python Webinar: Traits
Scientific Computing with Python Webinar: TraitsScientific Computing with Python Webinar: Traits
Scientific Computing with Python Webinar: Traits
 
groovy databases
groovy databasesgroovy databases
groovy databases
 
Assignment
AssignmentAssignment
Assignment
 
ES6 Overview
ES6 OverviewES6 Overview
ES6 Overview
 
sizeof(Object): how much memory objects take on JVMs and when this may matter
sizeof(Object): how much memory objects take on JVMs and when this may mattersizeof(Object): how much memory objects take on JVMs and when this may matter
sizeof(Object): how much memory objects take on JVMs and when this may matter
 
Node.js API pitfalls
Node.js API pitfallsNode.js API pitfalls
Node.js API pitfalls
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6
 
Current State of Coroutines
Current State of CoroutinesCurrent State of Coroutines
Current State of Coroutines
 
Rust-lang
Rust-langRust-lang
Rust-lang
 
concurrency with GPars
concurrency with GParsconcurrency with GPars
concurrency with GPars
 
PhpUnit - The most unknown Parts
PhpUnit - The most unknown PartsPhpUnit - The most unknown Parts
PhpUnit - The most unknown Parts
 
Ruby tricks2
Ruby tricks2Ruby tricks2
Ruby tricks2
 
Обзор фреймворка Twisted
Обзор фреймворка TwistedОбзор фреймворка Twisted
Обзор фреймворка Twisted
 
Introduction to c
Introduction to cIntroduction to c
Introduction to c
 
Kotlin Coroutines. Flow is coming
Kotlin Coroutines. Flow is comingKotlin Coroutines. Flow is coming
Kotlin Coroutines. Flow is coming
 
Dmxedit
DmxeditDmxedit
Dmxedit
 
Simulator customizing & testing for Xcode 9
Simulator customizing & testing for Xcode 9Simulator customizing & testing for Xcode 9
Simulator customizing & testing for Xcode 9
 

Viewers also liked

Viewers also liked (7)

Lviv training centre
Lviv training centreLviv training centre
Lviv training centre
 
Null Is the Saruman of Static Typing
Null Is the Saruman of Static TypingNull Is the Saruman of Static Typing
Null Is the Saruman of Static Typing
 
Material Design
Material DesignMaterial Design
Material Design
 
Innovation-forum
Innovation-forumInnovation-forum
Innovation-forum
 
TI townhall
TI townhallTI townhall
TI townhall
 
Pavlo Yuriychuk — Switching to Angular.js. Silk way
Pavlo Yuriychuk — Switching to Angular.js. Silk wayPavlo Yuriychuk — Switching to Angular.js. Silk way
Pavlo Yuriychuk — Switching to Angular.js. Silk way
 
Vitaliy Pelekh career-conversVitaliy Pelekh — Career conversations (PM Talk i...
Vitaliy Pelekh career-conversVitaliy Pelekh — Career conversations (PM Talk i...Vitaliy Pelekh career-conversVitaliy Pelekh — Career conversations (PM Talk i...
Vitaliy Pelekh career-conversVitaliy Pelekh — Career conversations (PM Talk i...
 

Similar to C++ 11 usage experience

Venturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
Venturing Into The Wild: A .NET Developer's Experience As A Ruby DeveloperVenturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
Venturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
Jon Kruger
 

Similar to C++ 11 usage experience (20)

Learning Java 1 – Introduction
Learning Java 1 – IntroductionLearning Java 1 – Introduction
Learning Java 1 – Introduction
 
Groovy
GroovyGroovy
Groovy
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
 
Google App Engine Developer - Day3
Google App Engine Developer - Day3Google App Engine Developer - Day3
Google App Engine Developer - Day3
 
All I Need to Know I Learned by Writing My Own Web Framework
All I Need to Know I Learned by Writing My Own Web FrameworkAll I Need to Know I Learned by Writing My Own Web Framework
All I Need to Know I Learned by Writing My Own Web Framework
 
C++ nothrow movable types
C++ nothrow movable typesC++ nothrow movable types
C++ nothrow movable types
 
Java7 New Features and Code Examples
Java7 New Features and Code ExamplesJava7 New Features and Code Examples
Java7 New Features and Code Examples
 
Os Secoske
Os SecoskeOs Secoske
Os Secoske
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
 
C++ theory
C++ theoryC++ theory
C++ theory
 
Jdbc
JdbcJdbc
Jdbc
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
 
JS Fest 2019 Node.js Antipatterns
JS Fest 2019 Node.js AntipatternsJS Fest 2019 Node.js Antipatterns
JS Fest 2019 Node.js Antipatterns
 
Nantes Jug - Java 7
Nantes Jug - Java 7Nantes Jug - Java 7
Nantes Jug - Java 7
 
Ruby is Awesome
Ruby is AwesomeRuby is Awesome
Ruby is Awesome
 
Backbone js
Backbone jsBackbone js
Backbone js
 
Venturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
Venturing Into The Wild: A .NET Developer's Experience As A Ruby DeveloperVenturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
Venturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
 
JQuery Presentation
JQuery PresentationJQuery Presentation
JQuery Presentation
 
Google Guava for cleaner code
Google Guava for cleaner codeGoogle Guava for cleaner code
Google Guava for cleaner code
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
 

More from GlobalLogic Ukraine

GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
GlobalLogic Ukraine
 

More from GlobalLogic Ukraine (20)

GlobalLogic JavaScript Community Webinar #18 “Long Story Short: OSI Model”
GlobalLogic JavaScript Community Webinar #18 “Long Story Short: OSI Model”GlobalLogic JavaScript Community Webinar #18 “Long Story Short: OSI Model”
GlobalLogic JavaScript Community Webinar #18 “Long Story Short: OSI Model”
 
Штучний інтелект як допомога в навчанні, а не замінник.pptx
Штучний інтелект як допомога в навчанні, а не замінник.pptxШтучний інтелект як допомога в навчанні, а не замінник.pptx
Штучний інтелект як допомога в навчанні, а не замінник.pptx
 
Задачі AI-розробника як застосовується штучний інтелект.pptx
Задачі AI-розробника як застосовується штучний інтелект.pptxЗадачі AI-розробника як застосовується штучний інтелект.pptx
Задачі AI-розробника як застосовується штучний інтелект.pptx
 
Що треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptx
Що треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptxЩо треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptx
Що треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptx
 
GlobalLogic Java Community Webinar #16 “Zaloni’s Architecture for Data-Driven...
GlobalLogic Java Community Webinar #16 “Zaloni’s Architecture for Data-Driven...GlobalLogic Java Community Webinar #16 “Zaloni’s Architecture for Data-Driven...
GlobalLogic Java Community Webinar #16 “Zaloni’s Architecture for Data-Driven...
 
JavaScript Community Webinar #14 "Why Is Git Rebase?"
JavaScript Community Webinar #14 "Why Is Git Rebase?"JavaScript Community Webinar #14 "Why Is Git Rebase?"
JavaScript Community Webinar #14 "Why Is Git Rebase?"
 
GlobalLogic .NET Community Webinar #3 "Exploring Serverless with Azure Functi...
GlobalLogic .NET Community Webinar #3 "Exploring Serverless with Azure Functi...GlobalLogic .NET Community Webinar #3 "Exploring Serverless with Azure Functi...
GlobalLogic .NET Community Webinar #3 "Exploring Serverless with Azure Functi...
 
Страх і сила помилок - IT Inside від GlobalLogic Education
Страх і сила помилок - IT Inside від GlobalLogic EducationСтрах і сила помилок - IT Inside від GlobalLogic Education
Страх і сила помилок - IT Inside від GlobalLogic Education
 
GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”
GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”
GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”
 
GlobalLogic QA Webinar “What does it take to become a Test Engineer”
GlobalLogic QA Webinar “What does it take to become a Test Engineer”GlobalLogic QA Webinar “What does it take to become a Test Engineer”
GlobalLogic QA Webinar “What does it take to become a Test Engineer”
 
“How to Secure Your Applications With a Keycloak?
“How to Secure Your Applications With a Keycloak?“How to Secure Your Applications With a Keycloak?
“How to Secure Your Applications With a Keycloak?
 
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
 
GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...
GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...
GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...
 
GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”
GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”
GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”
 
Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"
Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"
Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"
 
GlobalLogic Webinar "Introduction to Embedded QA"
GlobalLogic Webinar "Introduction to Embedded QA"GlobalLogic Webinar "Introduction to Embedded QA"
GlobalLogic Webinar "Introduction to Embedded QA"
 
C++ Webinar "Why Should You Learn C++ in 2021-22?"
C++ Webinar "Why Should You Learn C++ in 2021-22?"C++ Webinar "Why Should You Learn C++ in 2021-22?"
C++ Webinar "Why Should You Learn C++ in 2021-22?"
 
GlobalLogic Test Automation Live Testing Session “Android Behind UI — Testing...
GlobalLogic Test Automation Live Testing Session “Android Behind UI — Testing...GlobalLogic Test Automation Live Testing Session “Android Behind UI — Testing...
GlobalLogic Test Automation Live Testing Session “Android Behind UI — Testing...
 
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
 
GlobalLogic Azure TechTalk ONLINE “Marketing Data Lake in Azure”
GlobalLogic Azure TechTalk ONLINE “Marketing Data Lake in Azure”GlobalLogic Azure TechTalk ONLINE “Marketing Data Lake in Azure”
GlobalLogic Azure TechTalk ONLINE “Marketing Data Lake in Azure”
 

Recently uploaded

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
fonyou31
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
SoniaTolstoy
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 

Recently uploaded (20)

The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 

C++ 11 usage experience

  • 2.      Introduction: copying temporaries pitfall Moving constructors Perfect forwarding Extending horizons: tips & tricks Q&A
  • 3.  Find an error and propose a fix: vector<string>& getNames() { vector<string> names; names.push_back("Ivan"); names.push_back("Artem"); return names; }
  • 4.  Possible solutions: 1 void getNames(vector<string>& names) { names.push_back("Ivan"); names.push_back("Artem"); } vector<string> names; getNames(names); auto_ptr<vector<string> > names( getNames()); 2 auto_ptr<vector<string> > getNames() { auto_ptr<vector<string> > names( new vector<string>); names->push_back("Ivan"); names->push_back("Artem"); return names; } vector<string> const& names = getNames(); 3 vector<string> getNames() { vector<string> names; names.push_back("Ivan"); names.push_back("Artem"); return names; }
  • 5.  Compiler: Return Value Optimization (RVO); Named Return Value Optimization (NRVO). • •  Techniques: Copy-on-write (COW); “Move Constructors”: • •  Simulate temporary objects and treat them differently.
  • 8. lvalue  •  • identifies a non-temporary object. prvalue “pure rvalue” - identifies a temporary object or is a value not associated with any object. xvalue  • either temporary object or non-temporary object at the end of its scope. glvalue  •  • either lvalue or xvalue. rvalue either prvalue or xvalue.
  • 9. class Buffer { char* _data; size_t _size; // ... // copy the content from lvalue Buffer(Buffer const& lvalue) : _data(nullptr), _size(0) { // perform deep copy ... } // take the internals from rvalue Buffer(Buffer&& rvalue) : _data(nullptr), _size(0) { swap(_size, rvalue._size); swap(_data, rvalue._data); // it is vital to keep rvalue // in a consistent state } // ... Buffer getData() { /*...*/ } // ... Buffer someData; // ... initialize someData Buffer someDataCopy(someData); // make a copy Buffer anotherData(getData()); // move temporary
  • 10. class Configuration { // ... Configuration( Configuration const&); Configuration const& operator=( Configuration const& ); Configuration(Configuration&& ); Configuration const& operator=( Configuration&& ); // ... }; class ConfigurationStorage; class ConfigurationManger { // ... Configuration _current; // ... bool reload(ConfigurationStorage& ); // ... }; bool ConfigurationManager::reload( ConfigurationStorage& source ) { Configuration candidate = source.retrieve(); // OK, call move ctor if (!isValid(candidate)) { return false; } _current = candidate; // BAD, copy lvalue to lvalue _current = move(candidate); // OK, use move assignment return true; }
  • 11. Does not really move anything;  Does cast a reference to object to xvalue:  template<typename _T> typename remove_reference<_T>::type&& move(_T&& t) { return static_cast<typename remove_reference<_T>::type&&>(t); }  Does not produce code for run-time.
  • 12.     Move is an optimization for copy. Copy of rvalue objects may become move. Explicit move for objects without move support becomes copy. Explicit move objects of built-in types always becomes copy.
  • 13. Compiler does generate move constructor/assignment operator when:  • • • there is no user-defined copy or move operations (including default); there is no user-defined destructor (including default); all non-static members and base classes are movable.  Implicit move constructor/assignment operator does perform member-wise moving.  Force-generated move operators does perform member-wise moving: • dangerous when dealing with raw resources (memory, handles, etc.).
  • 14. class Configuration { // have copy & move operations implemented // ... }; class ConfigurationManger { // ... Configuration _current; // ... ConfigurationManager(Configuration const& defaultConfig) : _current(defaultConfig) // call copy ctor { } ConfigurationManager(Configuration&& defaultConfig) // : _current(defaultConfig) // BAD, call copy ctor : _current(move(defaultConfig)) // OK, call move ctor { } // ... };
  • 15. class Configuration { // have copy & move operations implemented // ... }; class ConfigurationManger { // ... Configuration _current; // ... template <class _ConfigurationRef> explicit ConfigurationManager(_ConfigurationRef&& defaultConfig) : _current(forward<_ConfigurationRef>(defaultConfig)) // OK, deal with either rvalue or lvalue { } // ... };
  • 16.  Normally C++ does not allow reference to reference types.  Template types deduction often does produce such types.  There are rules for deduct a final type then: • • • • T& &  T& T& &&  T& T&& &  T& T&& &&  T&&
  • 17. Just a cast as well;  Applicable only for function templates;  Preserves arguments lvaluesness/rvaluesness/constness/etc.  template<typename _T> _T&& forward(typename remove_reference<_T>::type& t) { return static_cast<_T&&>(t); } template<typename _T> _T&& forward(typename remove_reference<_T>::type&& t) { return static_cast<_T&&>(t); }
  • 18. class ConfigurationManger { template <class _ConfigurationType> ConfigurationManager(_ConfigurationType&& defaultConfig) : _current(forward<_ConfigurationType>(defaultConfig)) {} // ... }; // ... Configuration defaultConfig; ConfigurationManager configMan(defaultConfig); // _ConfigurationType => Configuration& // decltype(defaultConfig) => Configuration& && => Configuration& // forward => Configuration& && forward<Configuration&>(Configuration& ) // => Configuration& forward<Configuration&>(Configuration& ) ConfigurationManager configMan(move(defaultConfig)); // _ConfigurationType => Configuration // decltype(defaultConfig) => Configuration&& // forward => Configuration&& forward<Configuration>(Configuration&& )
  • 19.  Passing parameters to functions: class ConfigurationStorage { std::string _path; // ... template <class _String> bool open(_String&& path) { _path = forward<_String>(path); // ... } }; // ... string path("somewhere_near_by"); ConfigurationStorage storage; storage.open(path); // OK, pass as string const& storage.open(move(path)); // OK, pass as string&& storage.open("far_far_away"); // OK, pass as char const*
  • 20.  Passing parameters by value: class ConfigurationManger { Configuration _current; // ... bool setup( Configuration const& newConfig) { _current = newConfig; // make a copy } bool setup( Configuration&& newConfig) { _current = move(newConfig); // simply take it } }; Configuration config; configManager.setup(config); // pass by const& configManager.setup(move(config)); // pass by && class ConfigurationManger { Configuration _current; // ... bool setup( Configuration newConfig) { // ... _current = move(newConfig); // could just take it } }; Configuration config; configManager.setup(config); // make copy ahead configManager.setup(move(config)); // use move ctor
  • 21.  Return results: vector<string> getNamesBest() { vector<string> names; // ... return names; // OK, compiler choice for either of move ctor or RVO } vector<string> getNamesGood() { vector<string> names; // ... return move(names); // OK, explicit call move ctor } vector<string>&& getNamesBad() { vector<string> names; // ... return move(names); // BAD, return a reference to a local object }
  • 22.  Extending object life-time: vector<string> getNames() { vector<string> names; // ... return names; } // ... vector<string> const& names = getNames(); // vector<string>&& names = getNames(); // vector<string> names = getNames(); // vector<string>& names = getNames(); // vector<string>&& names = move(getNames());// OK, both C++03/C++11 OK, C++11: extends life-time OK, C++11: move construction BAD, dangling reference here BAD, dangling reference here
  • 23. The hardest work for move semantic support usually performed by the compiler and the Standard Library.  There is still a lot of space for apply move semantic explicitly for performance critical parts of the application:  • It is up to developer to ensure the code correctness when the move semantic used explicitly. • The best way to add move semantic support to own class is using pImpl idiom.