This document discusses C++ rvalue references and move semantics. It begins with an overview and definitions of lvalues and rvalues from C and how they evolved in C++11. It then covers value categories like prvalues and xvalues introduced in C++11. The document explains how rvalue references allow objects to be moved instead of copied by extending their lifetime. It also discusses how classes can implement move semantics by adding move constructors and assignment operators. The document notes many ways C++ and the standard library support move semantics, like optimized containers, algorithms, traits and perfect forwarding. It ends with some examples of how to incorrectly use rvalue references and move semantics.
Hot С++: Universal References And Perfect ForwardingAndrey Upadyshev
Detailed presentation of universal references and perfect forwarding introduced in C++11.
Extended version of "Hot C++11, Part 3 Universal References And Perfect Forwarding".
This is an overview of C++ (based on 1999 / 2003 standard) and its use in Object Oriented Programming. The presentation assumes that the audience knows C programming.
An operator is a symbol designed to operate on data.
They can be a single symbol, di-graphs, tri-graphs or keywords.
Operators can be classified in different ways.
This is similar to function overloading
••• Learn how to safely manage memory with smart pointers! •••
In this presentation you will learn:
▸ the dangers of using raw pointers for dynamic memory
▸ the difference between unique_ptr, shared_ptr, weak_ptr
▸ how to use factories to increase safety and performance
▸ when raw pointers are still needed
A function is a group of statements that together perform a task. Every C program has at least one function, which is main(), and all the most trivial programs can define additional functions. You can divide up your code into separate functions.
Hot С++: Universal References And Perfect ForwardingAndrey Upadyshev
Detailed presentation of universal references and perfect forwarding introduced in C++11.
Extended version of "Hot C++11, Part 3 Universal References And Perfect Forwarding".
This is an overview of C++ (based on 1999 / 2003 standard) and its use in Object Oriented Programming. The presentation assumes that the audience knows C programming.
An operator is a symbol designed to operate on data.
They can be a single symbol, di-graphs, tri-graphs or keywords.
Operators can be classified in different ways.
This is similar to function overloading
••• Learn how to safely manage memory with smart pointers! •••
In this presentation you will learn:
▸ the dangers of using raw pointers for dynamic memory
▸ the difference between unique_ptr, shared_ptr, weak_ptr
▸ how to use factories to increase safety and performance
▸ when raw pointers are still needed
A function is a group of statements that together perform a task. Every C program has at least one function, which is main(), and all the most trivial programs can define additional functions. You can divide up your code into separate functions.
Type Conversion, Precedence and AssociativityAakash Singh
This presentation is about Type Conversion, Precedence and Associativity which are important concepts for problem solving in programming languages like C, C++, Java, etc. It will surely help you to improve your knowledge.
Java abstract class & abstract methods,Abstract class in java
Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but contains no implementation. Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods.
“The .NET Framework class library is a library of classes, interfaces, and value types that provide access to system functionality. It is the foundation on which .NET Framework applications, components, and controls are built.”
Programming is hard. Programming correct C and C++ is particularly hard. Indeed, both in C and certainly in C++, it is uncommon to see a screenful containing only well defined and conforming code.Why do professional programmers write code like this? Because most programmers do not have a deep understanding of the language they are using.While they sometimes know that certain things are undefined or unspecified, they often do not know why it is so. In these slides we will study small code snippets in C and C++, and use them to discuss the fundamental building blocks, limitations and underlying design philosophies of these wonderful but dangerous programming languages.
This content has a CC license. Feel free to use it for whatever you want. You may download the original PDF file from: http://www.pvv.org/~oma/DeepC_slides_oct2012.pdf
[OLD VERSION, SEE DESCRIPTION FOR NEWER VERSION LINK] Hot C++: Rvalue Referen...Andrey Upadyshev
Newer version: https://www.slideshare.net/oliora/hot-c-rvalue-references-and-move-semantics-155638600
Detailed presentation of rvalue references and move semantics introduced in C++11.
Extended version of "Hot C++11, Part 1: Rvalue References And Move Semantics".
Type Conversion, Precedence and AssociativityAakash Singh
This presentation is about Type Conversion, Precedence and Associativity which are important concepts for problem solving in programming languages like C, C++, Java, etc. It will surely help you to improve your knowledge.
Java abstract class & abstract methods,Abstract class in java
Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but contains no implementation. Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods.
“The .NET Framework class library is a library of classes, interfaces, and value types that provide access to system functionality. It is the foundation on which .NET Framework applications, components, and controls are built.”
Programming is hard. Programming correct C and C++ is particularly hard. Indeed, both in C and certainly in C++, it is uncommon to see a screenful containing only well defined and conforming code.Why do professional programmers write code like this? Because most programmers do not have a deep understanding of the language they are using.While they sometimes know that certain things are undefined or unspecified, they often do not know why it is so. In these slides we will study small code snippets in C and C++, and use them to discuss the fundamental building blocks, limitations and underlying design philosophies of these wonderful but dangerous programming languages.
This content has a CC license. Feel free to use it for whatever you want. You may download the original PDF file from: http://www.pvv.org/~oma/DeepC_slides_oct2012.pdf
[OLD VERSION, SEE DESCRIPTION FOR NEWER VERSION LINK] Hot C++: Rvalue Referen...Andrey Upadyshev
Newer version: https://www.slideshare.net/oliora/hot-c-rvalue-references-and-move-semantics-155638600
Detailed presentation of rvalue references and move semantics introduced in C++11.
Extended version of "Hot C++11, Part 1: Rvalue References And Move Semantics".
••• Boost your code's performances using C++11 new features! •••
In this presentation you will learn:
▸ the difference between an Lvalue and Rvalue
▸ how to use std::move, std::forward, noexcept
▸ how to implement move semantics to avoid useless copies
▸ how to implement perfect forwarding for the factory pattern
Slides from my "Gentle Introduction to Modern C++" presentation from January 20, 2015 at the Dublin C/C++ User Group: www.meetup.com/cppdug/events/219787667/
The code examples are located here: https://github.com/mihaitodor/Presentations/tree/master/cppdug/20.01.2015
The C++ rvalue lifetime disaster. Arno Schödl ➠ CoreHard Autumn 2019corehard_by
Rvalue references have been with us since C++11. They have originally been introduced to make moving objects more efficient: the object an rvalue reference references is assumed to go out of scope soon and thus may have its resources scavenged without harm. The C++ standard library, for example std::cref or std::ranges, makes use of yet another aspect of rvalue references: since they go out of scope soon, it is assumed unsafe to hold on to them beyond the scope of the current function, while lvalue references are considered safe. We, too, found this assumption to be very useful for smart memory management, in particular in generic code. Unfortunately, the C++ language itself violates this assumption in at least two places. First, rvalues bind to const&. This means that innocent-looking functions taking a parameter by const& and passing it through in some way silently convert rvalues to lvalue references, hiding any lifetime limitation of the rvalues. std::min/max are two such examples. Worse still, every accessor member function returning a const& to a member suffers from this problem. Second, temporary lifetime extension is meant to make binding a temporary to a reference safe by extending the lifetime of the temporary. But this only works as long as the temporary is still a prvalue. If the temporary has been passed through a function, even it has been correctly passed through by rvalue reference, lifetime extension will no longer be invoked and we get a dangling reference. These problems are not merely theoretical. We have had hard-to-find memory corruption in our code because of these problems. In this talk, I will describe the problems in detail, present our library-only approach to mitigate the problems, and finally, make an impossible-to-ever-get-into-the-standard proposal of how to put things right.
Esoft Metro Campus - Programming with C++
(Template - Virtusa Corporate)
Contents:
Overview of C++ Language
C++ Program Structure
C++ Basic Syntax
Primitive Built-in types in C++
Variable types
typedef Declarations
Enumerated Types
Variable Scope
Constants/Literals
Storage Classes
Operators
Control Constructs
Functions
Math Operations in C++
Arrays
Multi-dimensional Arrays
Strings
C++ Pointers
References
Date and Time
Structures
Basic Input / Output
Classes and Objects
Inheritance
Overloading
Polymorphism
Interfaces
Files and Streams
Exception Handling
Dynamic Memory
Namespaces
Templates
Preprocessor
Multithreading
Globus Connect Server Deep Dive - GlobusWorld 2024Globus
We explore the Globus Connect Server (GCS) architecture and experiment with advanced configuration options and use cases. This content is targeted at system administrators who are familiar with GCS and currently operate—or are planning to operate—broader deployments at their institution.
GraphSummit Paris - The art of the possible with Graph TechnologyNeo4j
Sudhir Hasbe, Chief Product Officer, Neo4j
Join us as we explore breakthrough innovations enabled by interconnected data and AI. Discover firsthand how organizations use relationships in data to uncover contextual insights and solve our most pressing challenges – from optimizing supply chains, detecting fraud, and improving customer experiences to accelerating drug discoveries.
First Steps with Globus Compute Multi-User EndpointsGlobus
In this presentation we will share our experiences around getting started with the Globus Compute multi-user endpoint. Working with the Pharmacology group at the University of Auckland, we have previously written an application using Globus Compute that can offload computationally expensive steps in the researcher's workflows, which they wish to manage from their familiar Windows environments, onto the NeSI (New Zealand eScience Infrastructure) cluster. Some of the challenges we have encountered were that each researcher had to set up and manage their own single-user globus compute endpoint and that the workloads had varying resource requirements (CPUs, memory and wall time) between different runs. We hope that the multi-user endpoint will help to address these challenges and share an update on our progress here.
Software Engineering, Software Consulting, Tech Lead.
Spring Boot, Spring Cloud, Spring Core, Spring JDBC, Spring Security,
Spring Transaction, Spring MVC,
Log4j, REST/SOAP WEB-SERVICES.
Unleash Unlimited Potential with One-Time Purchase
BoxLang is more than just a language; it's a community. By choosing a Visionary License, you're not just investing in your success, you're actively contributing to the ongoing development and support of BoxLang.
How to Position Your Globus Data Portal for Success Ten Good PracticesGlobus
Science gateways allow science and engineering communities to access shared data, software, computing services, and instruments. Science gateways have gained a lot of traction in the last twenty years, as evidenced by projects such as the Science Gateways Community Institute (SGCI) and the Center of Excellence on Science Gateways (SGX3) in the US, The Australian Research Data Commons (ARDC) and its platforms in Australia, and the projects around Virtual Research Environments in Europe. A few mature frameworks have evolved with their different strengths and foci and have been taken up by a larger community such as the Globus Data Portal, Hubzero, Tapis, and Galaxy. However, even when gateways are built on successful frameworks, they continue to face the challenges of ongoing maintenance costs and how to meet the ever-expanding needs of the community they serve with enhanced features. It is not uncommon that gateways with compelling use cases are nonetheless unable to get past the prototype phase and become a full production service, or if they do, they don't survive more than a couple of years. While there is no guaranteed pathway to success, it seems likely that for any gateway there is a need for a strong community and/or solid funding streams to create and sustain its success. With over twenty years of examples to draw from, this presentation goes into detail for ten factors common to successful and enduring gateways that effectively serve as best practices for any new or developing gateway.
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Shahin Sheidaei
Games are powerful teaching tools, fostering hands-on engagement and fun. But they require careful consideration to succeed. Join me to explore factors in running and selecting games, ensuring they serve as effective teaching tools. Learn to maintain focus on learning objectives while playing, and how to measure the ROI of gaming in education. Discover strategies for pitching gaming to leadership. This session offers insights, tips, and examples for coaches, team leads, and enterprise leaders seeking to teach from simple to complex concepts.
Check out the webinar slides to learn more about how XfilesPro transforms Salesforce document management by leveraging its world-class applications. For more details, please connect with sales@xfilespro.com
If you want to watch the on-demand webinar, please click here: https://www.xfilespro.com/webinars/salesforce-document-management-2-0-smarter-faster-better/
Atelier - Innover avec l’IA Générative et les graphes de connaissancesNeo4j
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Allez au-delà du battage médiatique autour de l’IA et découvrez des techniques pratiques pour utiliser l’IA de manière responsable à travers les données de votre organisation. Explorez comment utiliser les graphes de connaissances pour augmenter la précision, la transparence et la capacité d’explication dans les systèmes d’IA générative. Vous partirez avec une expérience pratique combinant les relations entre les données et les LLM pour apporter du contexte spécifique à votre domaine et améliorer votre raisonnement.
Amenez votre ordinateur portable et nous vous guiderons sur la mise en place de votre propre pile d’IA générative, en vous fournissant des exemples pratiques et codés pour démarrer en quelques minutes.
Graspan: A Big Data System for Big Code AnalysisAftab Hussain
We built a disk-based parallel graph system, Graspan, that uses a novel edge-pair centric computation model to compute dynamic transitive closures on very large program graphs.
We implement context-sensitive pointer/alias and dataflow analyses on Graspan. An evaluation of these analyses on large codebases such as Linux shows that their Graspan implementations scale to millions of lines of code and are much simpler than their original implementations.
These analyses were used to augment the existing checkers; these augmented checkers found 132 new NULL pointer bugs and 1308 unnecessary NULL tests in Linux 4.4.0-rc5, PostgreSQL 8.3.9, and Apache httpd 2.2.18.
- Accepted in ASPLOS ‘17, Xi’an, China.
- Featured in the tutorial, Systemized Program Analyses: A Big Data Perspective on Static Analysis Scalability, ASPLOS ‘17.
- Invited for presentation at SoCal PLS ‘16.
- Invited for poster presentation at PLDI SRC ‘16.
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisGlobus
JASMIN is the UK’s high-performance data analysis platform for environmental science, operated by STFC on behalf of the UK Natural Environment Research Council (NERC). In addition to its role in hosting the CEDA Archive (NERC’s long-term repository for climate, atmospheric science & Earth observation data in the UK), JASMIN provides a collaborative platform to a community of around 2,000 scientists in the UK and beyond, providing nearly 400 environmental science projects with working space, compute resources and tools to facilitate their work. High-performance data transfer into and out of JASMIN has always been a key feature, with many scientists bringing model outputs from supercomputers elsewhere in the UK, to analyse against observational or other model data in the CEDA Archive. A growing number of JASMIN users are now realising the benefits of using the Globus service to provide reliable and efficient data movement and other tasks in this and other contexts. Further use cases involve long-distance (intercontinental) transfers to and from JASMIN, and collecting results from a mobile atmospheric radar system, pushing data to JASMIN via a lightweight Globus deployment. We provide details of how Globus fits into our current infrastructure, our experience of the recent migration to GCSv5.4, and of our interest in developing use of the wider ecosystem of Globus services for the benefit of our user community.
Code reviews are vital for ensuring good code quality. They serve as one of our last lines of defense against bugs and subpar code reaching production.
Yet, they often turn into annoying tasks riddled with frustration, hostility, unclear feedback and lack of standards. How can we improve this crucial process?
In this session we will cover:
- The Art of Effective Code Reviews
- Streamlining the Review Process
- Elevating Reviews with Automated Tools
By the end of this presentation, you'll have the knowledge on how to organize and improve your code review proces
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Globus
The U.S. Geological Survey (USGS) has made substantial investments in meeting evolving scientific, technical, and policy driven demands on storing, managing, and delivering data. As these demands continue to grow in complexity and scale, the USGS must continue to explore innovative solutions to improve its management, curation, sharing, delivering, and preservation approaches for large-scale research data. Supporting these needs, the USGS has partnered with the University of Chicago-Globus to research and develop advanced repository components and workflows leveraging its current investment in Globus. The primary outcome of this partnership includes the development of a prototype enterprise repository, driven by USGS Data Release requirements, through exploration and implementation of the entire suite of the Globus platform offerings, including Globus Flow, Globus Auth, Globus Transfer, and Globus Search. This presentation will provide insights into this research partnership, introduce the unique requirements and challenges being addressed and provide relevant project progress.
Listen to the keynote address and hear about the latest developments from Rachana Ananthakrishnan and Ian Foster who review the updates to the Globus Platform and Service, and the relevance of Globus to the scientific community as an automation platform to accelerate scientific discovery.
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteGoogle
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
👉👉 Click Here To Get More Info 👇👇
https://sumonreview.com/ai-pilot-review/
AI Pilot Review: Key Features
✅Deploy AI expert bots in Any Niche With Just A Click
✅With one keyword, generate complete funnels, websites, landing pages, and more.
✅More than 85 AI features are included in the AI pilot.
✅No setup or configuration; use your voice (like Siri) to do whatever you want.
✅You Can Use AI Pilot To Create your version of AI Pilot And Charge People For It…
✅ZERO Manual Work With AI Pilot. Never write, Design, Or Code Again.
✅ZERO Limits On Features Or Usages
✅Use Our AI-powered Traffic To Get Hundreds Of Customers
✅No Complicated Setup: Get Up And Running In 2 Minutes
✅99.99% Up-Time Guaranteed
✅30 Days Money-Back Guarantee
✅ZERO Upfront Cost
See My Other Reviews Article:
(1) TubeTrivia AI Review: https://sumonreview.com/tubetrivia-ai-review
(2) SocioWave Review: https://sumonreview.com/sociowave-review
(3) AI Partner & Profit Review: https://sumonreview.com/ai-partner-profit-review
(4) AI Ebook Suite Review: https://sumonreview.com/ai-ebook-suite-review
Navigating the Metaverse: A Journey into Virtual Evolution"Donna Lenk
Join us for an exploration of the Metaverse's evolution, where innovation meets imagination. Discover new dimensions of virtual events, engage with thought-provoking discussions, and witness the transformative power of digital realms."
4. Lvalue And Rvalue (how came from C)
• lvalue - may appear on the left hand side of an
assignment, represents storage region locator value, i.e.
evaluates to object identity.
• All the rest is non-lvalue or rvalue (because can appear
on the right hand side of assignment only)
!4
5. Lvalue And Rvalue, Example 1
int a = 42; // OK lvalue on left side of assignment
int b = 43; // and rvalue on right side
a = b; // OK, lvalue may be on any side of assignment
b = a; // OK, lvalue may be on any side of assignment
int c = a * b; // OK, rvalue on right side of assignment
a * b = 42; // err, rvalue on left hand side of assignment
int *p = &i; // OK, i is an lvalue
int *p1 = &43; // err, cannot take the address of an rvalue
!5
6. Value Categories (C++11)
• lvalue - is an expression that identifies a non-temporary
object
• prvalue ("pure" rvalue) - is an expression that identifies a
temporary object or is a value not associated with any
object (C++03 rvalue)
• Ex: The result of calling a function whose return type is
a value
• xvalue (an “eXpiring” value) - is an expression that
identifies expiring object, that is, the object that may be
moved from
• Ex: The result of calling a function whose return type is
an rvalue reference
!6
Simplified!
}rvalues
7. std::cout << &bar().member; // ?
Lvalue And Rvalue, Example 2
Foo& foo(); // `foo()` is lvalue
foo() = 42; // OK
std::cout << &foo(); // OK
Bar bar(); // `bar()` is prvalue
Bar && pub(); // `pub()` is xvalue
Bar b2 = bar(); // OK
bar() = b2; // cannot assign to an rvalue
std::cout << &bar(); // cannot take the address of an rvalue
std::cout << &pub(); // …
!7
std::cout << &bar().member; // reference to a member of an rvalue
// is an rvalue!
8. Lvalue References
void foo(const Bar& bar); //[1]
Binds to lvalue and rvalue. Can not modify bar.
void foo(Bar& bar); //[2]
Binds to lvalue only. Can modify bar. (Very old Visual C++ versions
bind it to rvalue too. But this does not conform to the Standard)
!8
Bar read_bar(const char *filename);
foo(read_bar(“bar.txt”)); ?
foo(read_bar(“bar.txt”)); // [1] => bar is const
9. Rvalue References
!9
void foo(const Bar& bar); //[1]
Binds to lvalue and rvalue. Can not modify bar.
void foo(Bar& bar); //[2]
Binds to lvalue only. Can modify bar.
void foo(Bar && bar); //[3]
Binds to rvalue only. Takes precedence over lvalue overloads. Can
modify bar.
void foo(const Bar && bar); //[4]
Binds to rvalue only. Takes precedence over lvalue overloads. Can not
modify bar. [Almost] has no useful meaning. Use const ref overload
instead.
foo(read_bar(“bar.txt”)); // [3] => bar is mutable!
10. Why Do I Need Them At All?
void foo(Bar && rv);
❖ In short: to use move semantics!
❖ Longer:
❖ Because rvalue references bind to rvalue, they can be
used to extend the lifetime of a modifiable temporary
(an rvalue is a temporary, remember?).
❖ You can do funny things with temporary, e.g. safely
steal any data you need from it (nobody cares, heh).
It’s called move semantics.
!10
12. Move Semantics In Example
Copying
MemBuf lv = rv;
class MemBuf { void *m_data; size_t m_size; ... };
!12
F1 23 4C DB 98 73 11 ...
rv
allocate
and copy
F1 23 4C DB 98 73 11 ...
lv contains a copy of rv's
content
lv
Moving
MemBuf lv = std::move(rv);
F1 23 4C DB 98 73 11 ...
rv
lv
lv grabs (steals) content of rv
rv in moved-from state
X
13. Moved-From Objects
❖ Moving-from does not abolish destructing. The object’s destructor
is be called anyway!
❖ Moved-from object should be placed in a valid but unspecified
state, so it is safe to:
❖ destroy it
❖ assign one a new value (is assignable)
❖ A type may provide more strong guaranty. E.g. there is guaranty
that moved-from STD smart pointers are empty.
!13
F1 23 4C DB 98 73 11 ...
rv
lv
X
14. Why Move Semantics?
The best possible performance for classes with expensive copy while
keeping the clear interface.
❖ std::vector<HugeObject> performing bad in C++03:
❖ Copies elements on insertion and even more on growing.
❖ Can be passed around only wrapped with smart pointer.
❖ So we used std::vector<std::shared_ptr<HugeObject>> or
boost::ptr_vector<HugeObject> to gain performance but got new problems:
❖ Extra allocation and extra level of indirection (performance!)
❖ Extra complexity
❖ Doesn’t work smoothly with STL algorithms (OK, ptr_vector does)
❖ Thanks to move semantics std::vector<HugeObject> become good in C++11
(finally!):
❖ Elements are moved on insertion and on growing
❖ No [smart] pointer involved overhead
❖ Clear and simple, STL algorithms works perfect
❖ Can be moved around
!14
16. Adding Move Semantics To a Class
❖ There are two new special member functions:
❖ Move constructor:
Foo::Foo(Foo&& op);
❖ Move assignment operator:
Foo& operator= (Foo&& op);
❖ Like copy ctor/assignment operator, but moves from its argument.
❖ The functions are compiler generated by default (use it!) but may be user
provided, explicitly defaulted or deleted.
❖ Compiler uses similar rules as for copy ctor/copy assignment operator
generation.
❖ Visual Studio before 2015 does not generate move ctor/move
assignment. You must do it manually.
!16
17. Forcing Move Semantics
template<class T>
void swap_opt(T& a, T& b)
{
T tmp(a);
a = b;
b = tmp;
}
Hm, copying…
std::move just casts lvalue to rvalue (no moving itself!) what allows a move semantics
to be used. Scott Meyers said that perhaps one should be called rvalue_cast
!17
template<class T>
void swap_opt(T& a, T& b)
{
T tmp(std::move(a));
a = std::move(b);
b = std::move(tmp);
}
Moving!!!
Let’s implement optimized swap that utilize move semantics.
For simplicity, assume that it will be applied only to movable types.
Forcing move semantics leaves moved from objects behind, so must be uses carefully:
std::string tmp("bla-bla");
std::string s(std::move(tmp));
std::cout << tmp; // Using of 'moved from' object (e.g. by mistake) for
// other then assigning. Undefined behavior for most types
19. Supported By STL
❖ C++11 STL is significantly extended to support rvalue references
and move semantics:
❖ All containers and other types storing user types (pair, tuple,
future, function, smart pointers etc) are move-aware.
❖ New algorithms: move, move_forward
❖ New iterator adapter: move_iterator
❖ Movable, non-copyable unique_ptr replaces flawy auto_ptr
(which is deprecated)
❖ Optimized swap for movable types
❖ New type traits
!19
20. Ref Qualifiers
❖ Member functions can be specified with ref-qualifier & or &&, placed
after cv-qualifier:
❖ const Foo& Bar::foo() const & { // [1]
return m_foo;
}
❖ Foo&& Bar::foo() && { // [2]
return std::move(m_foo); // `*this` is always
} // lvalue
❖ Allow to have different overloads for lvalue and rvalue (temporary).
❖ No ref-qualifier means “whatever” (for backward compatibility)
❖ A function with a ref-qualifier can not overload with a function without
one.
!20
21. Perfect Forwarding & Forwarding
References
❖ Perfect forwarding is finally possible!
❖ Thanks to forwarding (aka universal) references and new
reference collapsing rules:
❖ template<class P1, class P2>
void create_foo(P1 && p1, P2 && p2) {
Foo foo(std::forward<P1>(p1),
std::forward<P2>(p2));
…
}
❖ Looks even better with variadic templates (not a sarcasm!)
❖ It is a big topic for another talk
!21
22. Optimization
❖ Copy elision does elision of both copy and move
operations
❖ When copy elision is not applicable, compiler prefers
moving over copying.
!22
23. Special Member Functions
❖ Move constructor and move assignment operator aren’t generated if copy
constructor, copy assignment operator or destructor is explicitly declared.
❖ Copy constructor and copy assignment operator aren't generated if move
constructor or move assignment operator is explicitly declared
❖ Not supported before Visual Studio 2015
❖ Rule of three become rule of five:
If a class defines one of the following it should probably explicitly define all five:
•destructor
•copy constructor
•copy assignment operator
•move constructor
•move assignment operator
!23
25. Named Rvalue Reference Is Not an Rvalue
Foo::Foo(Bar && bar)
: m_bar(bar) {} //[1] Is something wrong?
Named rvalue reference identifies an object => it is lvalue.
i.e. bar is copied unless move semantics is forced
Foo::Foo(Bar && bar)
: m_bar(std::move(bar)) {} //[2] OK
Foo::Foo(Foo && rh)
: m_bar(rh.m_bar) {} //[3] copy, ref to lvalue member is an lvalue
Foo::Foo(Foo && rh)
: m_bar(std::move(rh.m_bar)) {} //[4] OK
// or even safer
: m_bar(std::move(rh).m_bar) {} //[5] OK, ref to rvalue member is
// rvalue
!25
26. Returning of Rvalue Reference
Foo && make_foo() { //[1] Is something wrong?
return Foo(42);
}
An rvalue reference is a reference. Returning a reference to a
local object is bad. Return by value instead
Foo make_foo() { //[2] OK
return Foo(42);
}
Return rvalue reference only when you really know that you need this. A right
example is std::move:
template<class T>
typename std::remove_reference<T>::type&& std::move(T && t) {
return static_cast<typename std::remove_reference<T>::type &&>(t);
}
!26
27. ❖ Applying std::move to a const object does
not activate move semantics! You quietly got
copy instead of move.
❖ const Foo f = make_foo();
return Bar(std::move(f));
// Moving of `f` is blocked
❖ std::move does not remove object constness
❖ No compilation error generated in such case.
❖ Confusing unjustified behavior. One can write
something like safe_move to protect himself.
std::move And Const Objects
!27
28. Move Semantics and RVO
!28
struct Foo {…};
Foo make_foo1() {
Foo r(…);
return std::move(r);
}
Everything correct?
RVO is blocked, r is moved or copied
Foo make_foo1() {
Foo r(…);
return r;
}
RVO is applied, no move or copy
29. Move Semantics and RVO
!29
struct Bar {…};
struct Foo {
Foo(const Bar& rh);
Foo(Bar && rh);
…
};
Foo make_foo2() {
Bar bar(…);
return bar;
}
Everything correct?
Actually it is `return Foo(bar)`. bar is copied
Foo make_foo2() {
Bar bar(…);
return std::move(bar);
}
Actually it is `return Foo(std::move(bar))`. bar is moved. We can’t get any better here
31. Move Semantics And Exception Safety
For good reason STL containers may copy elements internally unless
ones' move constructor doesn't throw. Special traits are used:
std::move_if_noexcept
std::is_nothrow_move_constructible
To get rid of copy, add noexcept to the move special functions (only
if function really doesn't throw, no cheating, please!):
Elephant(Elephant && op) noexcept;
Note that noexcept is not supported in Visual Studio before 2015, use
macro like BOOST_NOEXCEPT (<boost/config/suffix.hpp>):
Elephant(Elephant && op) BOOST_NOEXCEPT;
!31
32. Useful Links
Alex Allain, Move semantics and rvalue references in C++11
http://www.cprogramming.com/c++11/rvalue-references-and-move-semantics-in-c++11.html
Dave Abrahams, Exceptionally Moving!
http://web.archive.org/web/20130524084627/http://cpp-next.com/archive/2009/10/exceptionally-moving/
Stephan T. Lavavej, Don’t Help the Compiler
http://channel9.msdn.com/Events/GoingNative/2013/Don-t-Help-the-Compiler
Andrzej Krzemieński, Ref-qualifiers
https://akrzemi1.wordpress.com/2014/06/02/ref-qualifiers/
Max Galkin. C++ curiosities: one does not simply move a const object
http://yacoder.net/blog/2015/05/06/cpp-curiosities-one-does-not-simply-move-a-const-object/
C++ Reference
http://en.cppreference.com/w/
Value categories
https://en.cppreference.com/w/cpp/language/value_category
C++11 Standard (final plus minor editorial changes)
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf
!32