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

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 initKwang Woo NAM
 
Scientific Computing with Python Webinar: Traits
Scientific Computing with Python Webinar: TraitsScientific Computing with Python Webinar: Traits
Scientific Computing with Python Webinar: TraitsEnthought, Inc.
 
groovy databases
groovy databasesgroovy databases
groovy databasesPaul King
 
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 matterDawid Weiss
 
Node.js API pitfalls
Node.js API pitfallsNode.js API pitfalls
Node.js API pitfallsTorontoNodeJS
 
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 6Dmitry Soshnikov
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6Dmitry Soshnikov
 
concurrency with GPars
concurrency with GParsconcurrency with GPars
concurrency with GParsPaul King
 
PhpUnit - The most unknown Parts
PhpUnit - The most unknown PartsPhpUnit - The most unknown Parts
PhpUnit - The most unknown PartsBastian Feder
 
Обзор фреймворка Twisted
Обзор фреймворка TwistedОбзор фреймворка Twisted
Обзор фреймворка TwistedMaxim Kulsha
 
Introduction to c
Introduction to cIntroduction to c
Introduction to cSayed Ahmed
 
Kotlin Coroutines. Flow is coming
Kotlin Coroutines. Flow is comingKotlin Coroutines. Flow is coming
Kotlin Coroutines. Flow is comingKirill Rozov
 
Simulator customizing & testing for Xcode 9
Simulator customizing & testing for Xcode 9Simulator customizing & testing for Xcode 9
Simulator customizing & testing for Xcode 9Bongwon Lee
 

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

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 TypingGlobalLogic Ukraine
 
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 wayGlobalLogic Ukraine
 
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...GlobalLogic Ukraine
 

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

Learning Java 1 – Introduction
Learning Java 1 – IntroductionLearning Java 1 – Introduction
Learning Java 1 – Introductioncaswenson
 
#include iostream #include fstream #include algorithm #i.docx
#include iostream #include fstream #include algorithm #i.docx#include iostream #include fstream #include algorithm #i.docx
#include iostream #include fstream #include algorithm #i.docxajoy21
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownpartsBastian Feder
 
Google App Engine Developer - Day3
Google App Engine Developer - Day3Google App Engine Developer - Day3
Google App Engine Developer - Day3Simon Su
 
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 FrameworkBen Scofield
 
C++ nothrow movable types
C++ nothrow movable typesC++ nothrow movable types
C++ nothrow movable typesarvidn
 
Java7 New Features and Code Examples
Java7 New Features and Code ExamplesJava7 New Features and Code Examples
Java7 New Features and Code ExamplesNaresh Chintalcheru
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation JavascriptRamesh Nair
 
JS Fest 2019 Node.js Antipatterns
JS Fest 2019 Node.js AntipatternsJS Fest 2019 Node.js Antipatterns
JS Fest 2019 Node.js AntipatternsTimur Shemsedinov
 
Ruby is Awesome
Ruby is AwesomeRuby is Awesome
Ruby is AwesomeAstrails
 
Backbone js
Backbone jsBackbone js
Backbone jsrstankov
 
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 DeveloperJon Kruger
 
JQuery Presentation
JQuery PresentationJQuery Presentation
JQuery PresentationSony Jain
 
Google Guava for cleaner code
Google Guava for cleaner codeGoogle Guava for cleaner code
Google Guava for cleaner codeMite Mitreski
 

Similar to C++ 11 usage experience (20)

Learning Java 1 – Introduction
Learning Java 1 – IntroductionLearning Java 1 – Introduction
Learning Java 1 – Introduction
 
#include iostream #include fstream #include algorithm #i.docx
#include iostream #include fstream #include algorithm #i.docx#include iostream #include fstream #include algorithm #i.docx
#include iostream #include fstream #include algorithm #i.docx
 
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
 

More from GlobalLogic Ukraine

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”GlobalLogic Ukraine
 
Штучний інтелект як допомога в навчанні, а не замінник.pptx
Штучний інтелект як допомога в навчанні, а не замінник.pptxШтучний інтелект як допомога в навчанні, а не замінник.pptx
Штучний інтелект як допомога в навчанні, а не замінник.pptxGlobalLogic Ukraine
 
Задачі AI-розробника як застосовується штучний інтелект.pptx
Задачі AI-розробника як застосовується штучний інтелект.pptxЗадачі AI-розробника як застосовується штучний інтелект.pptx
Задачі AI-розробника як застосовується штучний інтелект.pptxGlobalLogic Ukraine
 
Що треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptx
Що треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptxЩо треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptx
Що треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptxGlobalLogic Ukraine
 
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...GlobalLogic Ukraine
 
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 Ukraine
 
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...GlobalLogic Ukraine
 
Страх і сила помилок - IT Inside від GlobalLogic Education
Страх і сила помилок - IT Inside від GlobalLogic EducationСтрах і сила помилок - IT Inside від GlobalLogic Education
Страх і сила помилок - IT Inside від GlobalLogic EducationGlobalLogic Ukraine
 
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 Ukraine
 
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”GlobalLogic Ukraine
 
“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 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
 
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 Ukraine
 
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”GlobalLogic Ukraine
 
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 Ukraine
 
GlobalLogic Webinar "Introduction to Embedded QA"
GlobalLogic Webinar "Introduction to Embedded QA"GlobalLogic Webinar "Introduction to Embedded QA"
GlobalLogic Webinar "Introduction to Embedded QA"GlobalLogic Ukraine
 
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 Ukraine
 
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 Ukraine
 
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 Ukraine
 
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”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

3.14.24 Gender Discrimination and Gender Inequity.pptx
3.14.24 Gender Discrimination and Gender Inequity.pptx3.14.24 Gender Discrimination and Gender Inequity.pptx
3.14.24 Gender Discrimination and Gender Inequity.pptxmary850239
 
Quantitative research methodology and survey design
Quantitative research methodology and survey designQuantitative research methodology and survey design
Quantitative research methodology and survey designBalelaBoru
 
Arti Languages Pre Seed Send Ahead Pitchdeck 2024.pdf
Arti Languages Pre Seed Send Ahead Pitchdeck 2024.pdfArti Languages Pre Seed Send Ahead Pitchdeck 2024.pdf
Arti Languages Pre Seed Send Ahead Pitchdeck 2024.pdfwill854175
 
PHARMACOGNOSY CHAPTER NO 5 CARMINATIVES AND G.pdf
PHARMACOGNOSY CHAPTER NO 5 CARMINATIVES AND G.pdfPHARMACOGNOSY CHAPTER NO 5 CARMINATIVES AND G.pdf
PHARMACOGNOSY CHAPTER NO 5 CARMINATIVES AND G.pdfSumit Tiwari
 
2024.03.16 How to write better quality materials for your learners ELTABB San...
2024.03.16 How to write better quality materials for your learners ELTABB San...2024.03.16 How to write better quality materials for your learners ELTABB San...
2024.03.16 How to write better quality materials for your learners ELTABB San...Sandy Millin
 
The OERs: Transforming Education for Sustainable Future by Dr. Sarita Anand
The OERs: Transforming Education for Sustainable Future by Dr. Sarita AnandThe OERs: Transforming Education for Sustainable Future by Dr. Sarita Anand
The OERs: Transforming Education for Sustainable Future by Dr. Sarita AnandDr. Sarita Anand
 
LEAD5623 The Economics of Community Coll
LEAD5623 The Economics of Community CollLEAD5623 The Economics of Community Coll
LEAD5623 The Economics of Community CollDr. Bruce A. Johnson
 
How to Customise Quotation's Appearance Using PDF Quote Builder in Odoo 17
How to Customise Quotation's Appearance Using PDF Quote Builder in Odoo 17How to Customise Quotation's Appearance Using PDF Quote Builder in Odoo 17
How to Customise Quotation's Appearance Using PDF Quote Builder in Odoo 17Celine George
 
THYROID HORMONE.pptx by Subham Panja,Asst. Professor, Department of B.Sc MLT,...
THYROID HORMONE.pptx by Subham Panja,Asst. Professor, Department of B.Sc MLT,...THYROID HORMONE.pptx by Subham Panja,Asst. Professor, Department of B.Sc MLT,...
THYROID HORMONE.pptx by Subham Panja,Asst. Professor, Department of B.Sc MLT,...Subham Panja
 
ASTRINGENTS.pdf Pharmacognosy chapter 5 diploma in Pharmacy
ASTRINGENTS.pdf Pharmacognosy chapter 5 diploma in PharmacyASTRINGENTS.pdf Pharmacognosy chapter 5 diploma in Pharmacy
ASTRINGENTS.pdf Pharmacognosy chapter 5 diploma in PharmacySumit Tiwari
 
The First National K12 TUG March 6 2024.pdf
The First National K12 TUG March 6 2024.pdfThe First National K12 TUG March 6 2024.pdf
The First National K12 TUG March 6 2024.pdfdogden2
 
Dhavni Theory by Anandvardhana Indian Poetics
Dhavni Theory by Anandvardhana Indian PoeticsDhavni Theory by Anandvardhana Indian Poetics
Dhavni Theory by Anandvardhana Indian PoeticsDhatriParmar
 
Plant Tissue culture., Plasticity, Totipotency, pptx
Plant Tissue culture., Plasticity, Totipotency, pptxPlant Tissue culture., Plasticity, Totipotency, pptx
Plant Tissue culture., Plasticity, Totipotency, pptxHimansu10
 
POST ENCEPHALITIS case study Jitendra bhargav
POST ENCEPHALITIS case study  Jitendra bhargavPOST ENCEPHALITIS case study  Jitendra bhargav
POST ENCEPHALITIS case study Jitendra bhargavJitendra Bhargav
 
Metabolism of lipoproteins & its disorders(Chylomicron & VLDL & LDL).pptx
Metabolism of  lipoproteins & its disorders(Chylomicron & VLDL & LDL).pptxMetabolism of  lipoproteins & its disorders(Chylomicron & VLDL & LDL).pptx
Metabolism of lipoproteins & its disorders(Chylomicron & VLDL & LDL).pptxDr. Santhosh Kumar. N
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - HK2 (...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - HK2 (...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - HK2 (...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - HK2 (...Nguyen Thanh Tu Collection
 
ICS2208 Lecture4 Intelligent Interface Agents.pdf
ICS2208 Lecture4 Intelligent Interface Agents.pdfICS2208 Lecture4 Intelligent Interface Agents.pdf
ICS2208 Lecture4 Intelligent Interface Agents.pdfVanessa Camilleri
 

Recently uploaded (20)

3.14.24 Gender Discrimination and Gender Inequity.pptx
3.14.24 Gender Discrimination and Gender Inequity.pptx3.14.24 Gender Discrimination and Gender Inequity.pptx
3.14.24 Gender Discrimination and Gender Inequity.pptx
 
t-test Parametric test Biostatics and Research Methodology
t-test Parametric test Biostatics and Research Methodologyt-test Parametric test Biostatics and Research Methodology
t-test Parametric test Biostatics and Research Methodology
 
Least Significance Difference:Biostatics and Research Methodology
Least Significance Difference:Biostatics and Research MethodologyLeast Significance Difference:Biostatics and Research Methodology
Least Significance Difference:Biostatics and Research Methodology
 
ANOVA Parametric test: Biostatics and Research Methodology
ANOVA Parametric test: Biostatics and Research MethodologyANOVA Parametric test: Biostatics and Research Methodology
ANOVA Parametric test: Biostatics and Research Methodology
 
Quantitative research methodology and survey design
Quantitative research methodology and survey designQuantitative research methodology and survey design
Quantitative research methodology and survey design
 
Arti Languages Pre Seed Send Ahead Pitchdeck 2024.pdf
Arti Languages Pre Seed Send Ahead Pitchdeck 2024.pdfArti Languages Pre Seed Send Ahead Pitchdeck 2024.pdf
Arti Languages Pre Seed Send Ahead Pitchdeck 2024.pdf
 
PHARMACOGNOSY CHAPTER NO 5 CARMINATIVES AND G.pdf
PHARMACOGNOSY CHAPTER NO 5 CARMINATIVES AND G.pdfPHARMACOGNOSY CHAPTER NO 5 CARMINATIVES AND G.pdf
PHARMACOGNOSY CHAPTER NO 5 CARMINATIVES AND G.pdf
 
2024.03.16 How to write better quality materials for your learners ELTABB San...
2024.03.16 How to write better quality materials for your learners ELTABB San...2024.03.16 How to write better quality materials for your learners ELTABB San...
2024.03.16 How to write better quality materials for your learners ELTABB San...
 
The OERs: Transforming Education for Sustainable Future by Dr. Sarita Anand
The OERs: Transforming Education for Sustainable Future by Dr. Sarita AnandThe OERs: Transforming Education for Sustainable Future by Dr. Sarita Anand
The OERs: Transforming Education for Sustainable Future by Dr. Sarita Anand
 
LEAD5623 The Economics of Community Coll
LEAD5623 The Economics of Community CollLEAD5623 The Economics of Community Coll
LEAD5623 The Economics of Community Coll
 
How to Customise Quotation's Appearance Using PDF Quote Builder in Odoo 17
How to Customise Quotation's Appearance Using PDF Quote Builder in Odoo 17How to Customise Quotation's Appearance Using PDF Quote Builder in Odoo 17
How to Customise Quotation's Appearance Using PDF Quote Builder in Odoo 17
 
THYROID HORMONE.pptx by Subham Panja,Asst. Professor, Department of B.Sc MLT,...
THYROID HORMONE.pptx by Subham Panja,Asst. Professor, Department of B.Sc MLT,...THYROID HORMONE.pptx by Subham Panja,Asst. Professor, Department of B.Sc MLT,...
THYROID HORMONE.pptx by Subham Panja,Asst. Professor, Department of B.Sc MLT,...
 
ASTRINGENTS.pdf Pharmacognosy chapter 5 diploma in Pharmacy
ASTRINGENTS.pdf Pharmacognosy chapter 5 diploma in PharmacyASTRINGENTS.pdf Pharmacognosy chapter 5 diploma in Pharmacy
ASTRINGENTS.pdf Pharmacognosy chapter 5 diploma in Pharmacy
 
The First National K12 TUG March 6 2024.pdf
The First National K12 TUG March 6 2024.pdfThe First National K12 TUG March 6 2024.pdf
The First National K12 TUG March 6 2024.pdf
 
Dhavni Theory by Anandvardhana Indian Poetics
Dhavni Theory by Anandvardhana Indian PoeticsDhavni Theory by Anandvardhana Indian Poetics
Dhavni Theory by Anandvardhana Indian Poetics
 
Plant Tissue culture., Plasticity, Totipotency, pptx
Plant Tissue culture., Plasticity, Totipotency, pptxPlant Tissue culture., Plasticity, Totipotency, pptx
Plant Tissue culture., Plasticity, Totipotency, pptx
 
POST ENCEPHALITIS case study Jitendra bhargav
POST ENCEPHALITIS case study  Jitendra bhargavPOST ENCEPHALITIS case study  Jitendra bhargav
POST ENCEPHALITIS case study Jitendra bhargav
 
Metabolism of lipoproteins & its disorders(Chylomicron & VLDL & LDL).pptx
Metabolism of  lipoproteins & its disorders(Chylomicron & VLDL & LDL).pptxMetabolism of  lipoproteins & its disorders(Chylomicron & VLDL & LDL).pptx
Metabolism of lipoproteins & its disorders(Chylomicron & VLDL & LDL).pptx
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - HK2 (...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - HK2 (...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - HK2 (...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - HK2 (...
 
ICS2208 Lecture4 Intelligent Interface Agents.pdf
ICS2208 Lecture4 Intelligent Interface Agents.pdfICS2208 Lecture4 Intelligent Interface Agents.pdf
ICS2208 Lecture4 Intelligent Interface Agents.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.