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
 
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
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownpartsBastian Feder
 

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 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

INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
FILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipinoFILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipinojohnmickonozaleda
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 

Recently uploaded (20)

INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
FILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipinoFILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipino
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 

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.