Download - Glimpses of C++0x
December, 2009
Glimpses of C++0x
Dr. Partha Pratim DasInterra Systems (India) Pvt. Ltd.
Language Features
24-Nov-09 2
Agenda
• What is C++0x?
• Select Language Features
24-Nov-09 3
What is C++0x?
BasicsBasics
24-Nov-09 4
What is C++0x?
• C++0x is the next ISO C++ standard. • Current C++ standard is referred to as C++98 (C++03)• Current C standard is referred to as C99• Current C++0x draft is SC22-N-4411.pdf. It comprises:
– Language Features– Standard Library Enhancements
• Expected to be ready for national votes in 2010. • After that another 18 month before ISO signs up. • No features are expected to be added or removed after
March 2010. • The name "C++0x" is a relict of the hope for a C++08 or
C++09. Now we should think of 'x' as hexadecimal.
24-Nov-09 5
Who decides on C++0x?• ISO Standards committee, SC22 WG21. • Committee meets 2/3 times a year for a week each time. • Countries have national standards bodies with C++ groups.
– Active – Canada, France, Germany, Switzerland, UK, and USA.– Less Active – Denmark, the Netherlands, Japan, Norway, Spain.
• Work goes on offline and recorded as committee papers on the WG21 website.
• There are sub-working groups, such as "Core", "Library", "Evolution", and "Concurrency."
• The Main committee as a whole votes (one member one vote) and if something is accepted the nations vote.
• The committee has formal liaison with the C standards group (SC22 WG14), POSIX, and several other groups.
24-Nov-09 6
What are the aims of C++0x?
• C++ is a general-purpose programming language with a bias towards systems programming that – is a better C – supports data abstraction – supports object-oriented programming – supports generic programming
24-Nov-09 7
What are the aims of C++0x?
• Make C++ a better language for systems programming and library building – Avoid providing specialized facilities (e.g. numeric
computation or Windows-style application development).
• Make C++ easier to teach and learn – Through increased uniformity, stronger guarantees, and
facilities supportive of novices • Maintain very stringent compatibility constraints.
– Only very rarely break standards conforming code, though that's done when a new keyword (e.g. static_assert, nullptr, and constexpr) is introduced.
24-Nov-09 8
What are the design goals of C++0x?
• Maintain stability and compatibility
• Prefer libraries to language extensions
• Prefer generality to specialization
• Support both experts and novices
• Increase type safety
• Improve performance and ability to work directly with hardware
• Fit into the real world
24-Nov-09 9
What are the design goals of C++0x?
• Systems programming – improve the support for close-to-the-hardware programming (e.g. low-
level embedded systems programming) and efficiency. – Examples are constexpr, std::array, and generalized PODs.
• Generic programming – GP is among the great success stories of C++98; we needed to improve
support for it based on experience. – Examples are auto and template aliases.
• Machine model and concurrency – provide stronger guarantees for and better facilities for using modern
hardware (e.g. multicores and weakly coherent memory models). – Examples are the thread ABI, thread-local storage, and the atomics ABI.
• Library building – remove limitations, inefficiencies, and irregularities from the abstraction
mechanisms. – Examples are inline namespace, inherited constructors, and rvalue
references.
24-Nov-09 10
C++0x: Language Features• __cplusplus • alignments • attributes • atomic operations• auto• C99 features• enum class• copying and rethrowing
exceptions • constant expressions• decltype • defaulted and deleted functions• delegating constructors • Dynamic Initialization and
Destruction with Concurrency
• explicit conversion operators
• extended integer types
• extern templates
• for statement; see range for statement
• suffix return type syntax (extended function declaration syntax)
• in-class member initializers
• inherited constructors
• initializer lists (uniform and general initialization)
• lambdas
24-Nov-09 11
C++0x: Language Features• local classes as template
arguments • long long integers • memory model • move semantics; see rvalue
references • Inline namespace • Preventing narrowing • null pointer (nullptr) • PODs (generalized) • range for statement • raw string literals • right-angle brackets • rvalue references
• Simple SFINAE (Substitution Failure Is Not An Error) rule
• static (compile-time) assertions (static_assert)
• template alias • template typedef; see template
alias • thread-local storage
(thread_local) • unicode characters • Uniform initialization syntax
and semantics • unions (generalized) • user-defined literals • variadic templates
24-Nov-09 12
C++0x: Standard Library• abandoning a process • Improvements to algorithms • array • async() • atomic operations • Condition variables • Improvements to containers • function and bind • forward_list (a singly-liked list) • future and promise • garbage collection ABI • hash_tables (unordered_map) • metaprogramming and type
traits • Mutual exclusion
• random number generators
• regex (regular expression library)
• scoped allocators
• shared_ptr
• smart pointers
• threads
• Time utilities
• tuple
• unique_ptr
• unordered_map
• weak_ptr
• system error
24-Nov-09 13
C++0x: Compiler Support
• These have varied Language and Library Support– Gnu C++ (GCC 4.5)– Microsoft Visual C++ (VC10 Beta 2)– Sun C++– Intel C++– IBM XL C++
• Good Library Support exists in– Boost
24-Nov-09 14
Select Language Features
24-Nov-09 15
__cplusplus
24-Nov-09 16
__cplusplus• In C++98
• In C++0x, it will be defined as a different (greater) value
#define __cplusplus 199711L
24-Nov-09 17
long long – a longer integer (C99)
24-Nov-09 18
long long: a longer integer• An integer that's at least 64 bits long.
• There are no long long longs
• long cannot be spelled short long long.
• long long is in C99
long long x = 9223372036854775807LL;
24-Nov-09 19
Right angle brackets
24-Nov-09 20
right angle brackets• Consider:
• In C++98 this is a syntax error because there is no space between the two >s.
• C++0x recognizes such > as a correct termination of two template argument lists.
list<vector<string>> lvs;
24-Nov-09 21
static_assert
24-Nov-09 22
static_assert: static (compile-time) assertions
• A static (compile time) assertion consists of a constant expression and a string literal:
• The compiler evaluates the expression and writes the string as an error message if the expression is false (assertion failed).
static_assert(expression,string);
static_assert(sizeof(long) >= 8,
"64-bit support required for this library.");
struct S { X m1; Y m2; };
static_assert(sizeof(S)==sizeof(X)+sizeof(Y),
"unexpected padding in S");
24-Nov-09 23
static_assert: static (compile-time) assertions
• Cannot work for runtime checks:
• Need to throw exception
int f(int* p, int n)
{
static_assert(p==0,"p is not null");
// error: static_assert() expression
// not a constant expression
// ...
}
24-Nov-09 24
auto – Type Inference
24-Nov-09 25
auto – Type Inference• auto deduces the type of a variable from its
initializer expression.
• auto keyword can occur as a simple type specifier (useable with cv-qualifiers, *, &)
• The old meaning of auto ("this is a local variable") is redundant and unused
• Semantics of auto should follow exactly the rules of template argument deduction.
auto x = 3.14; // x has type double
24-Nov-09 26
auto: Examplesint foo();auto x1 = foo(); // x1 : intconst auto& x2 = foo(); // x2 : const int&auto& x3 = foo(); // x3 : int&:
// error, cannot bind a // reference to a temporary
float& bar();auto y1 = bar(); // y1 : floatconst auto& y2 = bar(); // y2 : const float&auto& y3 = bar(); // y3 : float&
A* fii()auto* z1 = fii(); // z1 : A*auto z2 = fii(); // z2 : A*auto* z3 = bar(); // error, bar does not
// return a pointer type
24-Nov-09 27
auto – Use
• Where type of initializer is not clear up-front– Inside template functions
• When the type is a lot of typing– Nested template types
24-Nov-09 28
auto: Use• In C++98
• In C++0xtemplate<class T> void printall(const vector<T>& v) {
for (auto p = v.begin(); p!=v.end(); ++p) cout << *p << "\n";
}
template<class T> void printall(const vector<T>& v) {
for (typename vector<T>::const_iterator p = v.begin(); p!=v.end(); ++p) cout << *p << "\n";
}
24-Nov-09 34
decltype
24-Nov-09 35
decltype: the type of an expression• decltype(E) is the type ("declared type") of
the name or expression E and can be used in declarations.
int i;const int&& foo();struct A { double x; }const A* a = new A();
decltype(i); // type is intdecltype(foo()); // type is const int&&decltype(a->x); // type is double
24-Nov-09 36
decltype
• typeof (declared type) has been popular in generic programming.
• typeof implementations in actual use are incomplete and incompatible
• Standard is opting for decltype.
• decltype is really needed for something that is not a variable, such as a return type.
• For the type for a variable about to be initialized auto is often a simpler choice.
24-Nov-09 37
decltype: Examples
void f(const vector<int>& a, vector<float>& b) { typedef decltype(a[0]*b[0]) Tmp; for (int i=0; i<b.size(); ++i) {
Tmp* p = new Tmp(a[i]*b[i]); // ... } // ...
}
#include <functional>
template<class T, class U>auto mul(T x, U y) -> decltype( x*y ) { return x*y;}
24-Nov-09 39
Suffix Return Type Syntax
24-Nov-09 40
Suffix Return Type Syntax• Use decltype to specify return types that
depend on the types of function arguments
• Argument names are not in scope!
• Use hack – works for all types
• New syntax solves
template <class T, class U> decltype((*(T*)0)+(*(U*)0)) add(T t, U u);
template <class T, class U> decltype(t+u) add(T t, U u);
template <class T, class U> auto add(T t, U u) −> decltype(t + u);auto add(auto x, auto y) { return x + y; } // short-cut
24-Nov-09 41
Defaulted or Deleted Functions
24-Nov-09 42
defaulted or deleted functions• Common idiom for Prohibit Copy:
• Idiom to Prohibit Copy is now expressed directly:
class X { // ... private:
X& operator=(const X&); // No definition X(const X&);
};
class X { // ... X& operator=(const X&) = delete; // No copying X(const X&) = delete;
};
24-Nov-09 43
defaulted or deleted functions• When we want the default, we say:
• Being explicit about the default is obviously redundant, but certainly more expressive.
• The "default" mechanism can be used for any function that has a default.
class Y { // ... Y& operator=(const Y&) = default; // default
// copy semantics Y(const Y&) = default;
}
24-Nov-09 44
defaulted or deleted functions• The "delete" mechanism can be used for
any function. For example, to eliminate an undesired conversion:
struct Z { // ... Z(long long); // can initialize with
// an long long Z(long) = delete; // but not anything less
};
24-Nov-09 45
enum class
24-Nov-09 46
enum: C++98
• C++ enums have 3 Problems: – Implicitly convert to int
• Cause errors when integer is not desired.
– Export the enumerators to the outer scope• Cause name clashes.
– Underlying type cannot be specified• Cause confusion
• Compatibility problems, and
• Makes forward declaration impossible.
24-Nov-09 47
enum class:scoped & strongly typed enum
• enum classes ("strong enums") – Are strongly typed and scoped.– Address problems of conventional enums
// traditional enum enum Alert { green, yellow, election, red };
// scoped and strongly typed enum // no export of enumerator names to enclosing scope // no implicit conversion to int enum class Color { red, blue };
enum class TrafficLight { red, yellow, green };
24-Nov-09 48
enum class: Scoped Examples
• Traditional enums work as usual, but one can now optionally qualify with the enum name.
Alert a = 7; // error (as ever in C++) Color c = 7; // error: no int->Color conversion
int a2 = red; // ok: Alert->int conversion int a3 = Alert::red; // error in C++98;
// ok in C++0x int a4 = blue; // error: blue not in scope int a5 = Color::blue; // error: not Color->int
// conversion Color a6 = Color::blue; // ok
24-Nov-09 49
enum class: Underlying Type• Specify the underlying type
– Simpler interoperability and – Guaranteed sizes.
• The underlying type must be – One of the signed or unsigned integer types– The default is int.
24-Nov-09 50
enum class: Underlying Type• Examples:
// compact representation enum class Color : char { red, blue };
// by default, the underlying type is int enum class TrafficLight { red, yellow, green };
// how big is an E? ("implementation defined") enum E { E1 = 1, E2 = 2, Ebig = 0xFFFFFFF0U }; // now we can be specific enum EE : unsigned long {
EE1 = 1, EE2 = 2, EEbig = 0xFFFFFFF0U };
24-Nov-09 51
enum class: Forward Declaration
// (forward) declaration enum class Color_code : char;
// use of forward declaration void foobar(Color_code* p); // ...
// definition enum class Color_code : char
{ red, yellow, green, blue };
24-Nov-09 53
Constant Expression
24-Nov-09 54
constexpr: generalized and guaranteed constant expression
• The constexpr mechanism – provides more general constant expressions – allows constant expressions involving user-
defined types – provides a way to guarantee that an
initialization is done at compile time
24-Nov-09 55
constexpr
• Function must be of a simple form – Evaluated at compile time if given constant expressions arguments.
enum Flags { good=0, fail=1, bad=2, eof=4 }; constexpr int operator|(Flags f1, Flags f2) {
return Flags(int(f1)|int(f2)); }
void f(Flags x) { switch (x) {
case bad: /* ... */ break; case eof: /* ... */ break; case bad|eof: /* ... */ break; default: /* ... */ break;
} }
24-Nov-09 56
constexpr
• constexpr in front of a variable definition – requires expression to be evaluated at compile time and– implies const
constexpr int x1 = bad|eof; // ok
void f(Flags f3) { constexpr int x2
= bad|f3; // error: // can't evaluate // at compile time
int x3 = bad|f3; // ok }
24-Nov-09 57
constexpr• Compile-time evaluation guarantee allow global objects to
be placed in read-only storage.
• Works for objects with constructors simple enough to be constexpr and expressions involving such objects:
struct Point { int x,y; constexpr Point(int xx, int yy):
x(xx), y(yy) { } };
constexpr Point origo(0,0); constexpr int z = origo.x; constexpr Point a[] =
{Point(0,0), Point(1,1), Point(2,2)}; constexpr x = a[1].x; // x becomes 1
24-Nov-09 58
Initializer List
24-Nov-09 59
Initializer List
• Mechanism for accepting a {}-list is a constructor with an argument of type std::initializer_list<T>.
vector<double> v = { 1, 2, 3.456, 99.99 };
list<pair<string,string>> languages = { {"Nygaard", "Simula"}, {"Richards", "BCPL"}, {"Ritchie", "C"} };
map<vector<string>,vector<int>> years = { { {"Maurice", "Vincent", "Wilkes"},
{1913, 1945, 1951, 1967, 2000} }, { {"Martin", "Richards"},
{1982, 2003, 2007} }, { {"David", "John", "Wheeler"},
{1927, 1947, 1951, 2004} } };
24-Nov-09 60
Initializer List• The initializer list can be of arbitrary length,
but must be homogeneous (all elements must be of a the template argument type, T, or convertible to T).
void f(initializer_list<int>);
f({1,2}); f({23,345,4567,56789}); f({}); // the empty list f{1,2}; // error: function call ( ) missing
years.insert({{"Bjarne","Stroustrup"}, {1950, 1975, 1985}});
24-Nov-09 63
Initializer List• std::vector …
vector<vector<double>> vs = { vector<double>(10), // ok: explicit construction
// (10 elements) vector<double>{10}, // ok explicit construction
// (1 element, 10)10 // error: vector's constructor
// is explicit };
24-Nov-09 64
Initializer List• A function can access the initializer_list as an immutable
sequence.
• A constructor that takes a single argument of type std::initializer_list is called an initializer-list constructor.
• The standard library containers, string, and regex have initializer-list constructors
• Initializer-list can be used as a Range.
void f(initializer_list<int> args) { for (auto p=args.begin(); p!=args.end(); ++p) cout << *p << "\n";
}
24-Nov-09 65
In–Class Member Initialization
24-Nov-09 66
In-class Member Initializations• In C++98, only static const members of integral
types can be initialized in-class, and the initializer has to be a constant expression
int var = 7; class X {
static const int m1 = 7; // ok const int m2 = 7; // error: not static static int m3 = 7; // error: not const static const int m4 = var; // error: initializer not
// constant expression static const string m5 =
"odd"; // error: not integral // type
// ... };
24-Nov-09 67
In-class Member Initializations• In C++0x, allow:
• To mean:
class A { public:
int a = 7; };
class A { public:
int a; A() : a(7) {}
};
24-Nov-09 68
In-class Member Initializations• For multiple Constructors:
• To mean:
class A { public:
A(): a(7), b(5), hash_algorithm("MD5"), s("Constructor run") {}
A(int a_val) : a(a_val), b(5), hash_algorithm("MD5"), s("Constructor run") {}
A(D d) : a(7), b(g(d)), hash_algorithm("MD5"), s("Constructor run") {}
int a, b; private:
HashingFunction hash_algorithm; // Hash std::string s; // State
};
24-Nov-09 69
In-class Member Initializations• Simplify:
• To mean:
class A { public:
A(){} A(int a_val) : a(a_val) {} A(D d) : b(g(d)) {} int a = 7, b = 5;
private: HashingFunction hash_algorithm{"MD5“}; // Hash std::string s{"Constructor run“}; // State
};
24-Nov-09 70
Uniform Initialization
24-Nov-09 71
Uniform Initialization Syntax & Semantics
• C++98 offers context-dependent ways for initializing an object
string a[] = {"foo", "bar"}; // ok: initialize arrayvector<string> v = {"foo", "bar"}; // error: initializer list
// for non-aggregate vector void f(string a[]); f( { "foo", " bar" } ); // syntax error: block as argument
int a = 2; // "assignment style" int[] aa = { 2, 3 }; // assignment style with list complex z(1,2); // "functional style" initialization x = Ptr(y); // "functional style" for
// conversion/cast/construction
int a(1); // variable definition int b(); // function declaration int b(foo); // variable definition or
// function declaration
24-Nov-09 72
Uniform Initialization Syntax & Semantics
• C++0x allow {}-initializer lists for all initializations
X x1 = X{1,2}; X x2 = {1,2}; // the = is optional X x3{1,2}; X* p = new X{1,2}; struct D : X {
D(int x, int y) :X{x,y} { /* ... */ }; };
struct S { int a[3]; S(int x, int y, int z) :a{x,y,z}
{ /* ... */ }; // solution to old problem
};
24-Nov-09 73
Uniform Initialization Syntax & Semantics
• X{a} constructs the same value in every context (where legal)
X x{a}; X* p = new X{a}; z = X{a}; // use as cast f({a}); // function argument (of type X) return {a}; // function return value
// (function returning X)
24-Nov-09 74
Prevent Narrowing
24-Nov-09 75
Preventing Narrowing• C++98 implicitly truncates.
• In C++0x, {} initialization doesn't narrow:
int x = 7.3; // Ouch! void f(int); f(7.3); // Ouch!
int x1 = {7.3}; // error: narrowing
double d = 7; int x2{d}; // error: narrowing (double to int)
// ok: even though 7 is an int, this is not narrowing char x3{7};
// error: double to int narrowingvector<int> vi = { 1, 2.3, 4, 5.6 };
24-Nov-09 76
for Range
24-Nov-09 77
Range for statement
• Iterates through a "range"– STL-sequence defined by a begin() and end(). – All standard containers – std::string, – an initializer list, – an array, and – anything (like istream) for which begin() and
end() are defined
24-Nov-09 78
Range for statement: Examples
• The begin() (and end()) can be a member to be called x.begin() or a free-standing function to be called begin(x).
void f(const vector<double>& v) { for (auto x : v) cout << x << '\n'; for (auto& x : v) ++x; // use a reference to
// change the value }
for (const auto x : { 1,2,3,5,8,13,21,34 }) cout << x << '\n';
24-Nov-09 79
Delegating Constructor
24-Nov-09 80
Delegating Constructors• In C++98, two constructors do the same
thing with repeat or call of "init() function." class X {
int a; validate(int x) {
if (0<x && x<=max) a=x; else throw bad_X(x); }
public: X(int x) { validate(x); } X() { validate(42); } X(string s) {
int x = lexical_cast<int>(s); validate(x); }
// ... };
24-Nov-09 81
Delegating Constructors• In C++0x, define one constructor in terms
of another:
class X { int a;
public: X(int x) {
if (0<x && x<=max) a=x; else throw bad_X(x); }
X() :X{42} { } X(string s) :X{lexical_cast<int>(s)} { } // ...
};
24-Nov-09 82
Inherited Constructor
24-Nov-09 83
Inherited Constructors
• In C++98, we can "lift" a set of overloaded functions from a base class to derived class:
• Lifting does not work for Constructors
struct B { void f(double); }; struct D : B { void f(int); }; B b; b.f(4.5); // fine D d; d.f(4.5); // calls D::f(int) with argument 4!
struct B { void f(double); }; struct D : B {
using B::f; // bring all f()s from B into scope void f(int); // add a new f()
}; B b; b.f(4.5); // fine D d; d.f(4.5); // fine: calls D::f(double)
// which is B::f(double)
24-Nov-09 84
Inherited Constructorsclass Base {
Base(int);};class Derived : public Base { public:
using Base::f; // lift Base's f to Derived's scope // -- works in C++98
void f(char); // provide a new f void f(int); // prefer this f to Base::f(int)
using Base::Base;// lift Base’s constr’s to Derived's// scope -- C++0x only
Derived(char); // provide a new constructor Derived(int); // prefer this constructor to
// Base::Base(int) // ...
};
24-Nov-09 85
Inherited Constructors: Initialization Slip
• Use Member Intializer
struct B1 { B1(int) { } }; struct D1 : B1 {
using B1::B1; // implicitly declares D1(int) int x;
}; void test() {
D1 d(6); // Oops: d.x is not initialized D1 e; // error: No default constructor
}
struct B1 { B1(int) { } }; struct D1 : B1 {
using B1::B1; // implicitly declares D1(int) int x{0}; // x is initialized
}; void test() { D1 d(6); // d.x is 0 }
24-Nov-09 86
nullptr
24-Nov-09 87
nullptr: A null pointer literal• nullptr
– is a reserved word. – is a literal, just like 1 and true.– address of nullptr itself can-not be taken (No memory)– designates a constant rvalue of type decltype(nullptr) or nullptr_t.
• typedef decltype(nullptr) nullptr_t;
• nullptr_t – is not a reserved word. It is defined in <cstddef>. – is a POD type – is convertible to both a pointer type and a pointer-to-member type. – has equivalent objects with identical behavior that
• may differ in cv-qualification• may differ in being rvalues or lvalues• may be be copied and thrown.
24-Nov-09 88
nullptr: Examplechar* p = nullptr; int* q = nullptr; char* p2 = 0; // 0 still works and p==p2
void f(int); void f(char*);
f(0); // call f(int) f(nullptr); // call f(char*)
void g(int); g(nullptr); // error: nullptr is not an int int i = nullptr; // error nullptr is not an int
if(n2 == 0); // evaluates to true if(n2 == nullptr); // error if(nullptr); // error, no conversion to bool if(nullptr == 0); // error
24-Nov-09 89
Rvalue references
24-Nov-09 90
Rvalue references• Lvalue: used on the left-hand side of an assignment• Rvalue: Used on the right-hand side of an assignment• Christopher Strachey
– Introduced Lvalue / Rvalue notions– Father of C++'s distant ancestor CPL and – Denotational Semantics
• In C++98, allowed reference bindings are:– Non-const references can bind to Lvalue, – Const references can bind to Lvalue – Const references can bind to Rvalue
• In C++98, disallowed reference bindings are:– No reference can bind to a Non-const Rvalue. – Protects against uses of temporaries after their destruction
24-Nov-09 91
Rvalue reference
• If that incr(0) were allowed– Some temporary that nobody ever saw would
be incremented or – The value of 0 would become 1.
void incr(int& a) { ++a; } int i = 0; incr(i); // i becomes 1 incr(0); // error: 0 in not an lvalue
24-Nov-09 92
Rvalue reference• Consider:
• swap would be expensive if T is a type (like string and vector)
• Standard Library, use specializations of string and vector swap()
• Interestingly: We didn't want any copies at all. We just wanted to move the values of a, b, and tmp.
template<class T> swap(T& a, T& b) // “typical swap" {
T tmp(a);// now we have two copies of a a = b; // now we have two copies of b b = tmp; // now we have two copies of tmp (aka a)
}
24-Nov-09 93
Rvalue reference: move semantics• Move Constructor & Move Assignment: template<class T> class vector {
// ... vector(const vector&); // copy constructor vector(vector&&); // move constructor vector& operator=(const vector&); // copy assignment vector& operator=(vector&&); // move assignment
}; // move constructor and move assignment takes non-const && // they can, and usually do, write to their argument
24-Nov-09 94
Copy vs Move Semantics• C and C++ are built on copy semantics.
– Move semantics augments copy semantics.
• A general user defined class might be – both copyable and movable, – one or the other, or – neither.
• A copy leaves the source unchanged• A move leaves the source in a consistent state• Choose move to allow any state of the source• For PODs, move and copy are identical operations
– MOV R1, R2 // Means copy R2 to R1
24-Nov-09 95
Rvalue reference: move semantics• The && indicates an "rvalue reference".
• An rvalue reference can bind to an rvalue (but not to an lvalue)
X a; X f(); X& r1 = a; // bind r1 to a (an lvalue) X& r2 = f(); // error: f() is an rvalue;
// can't bind X&& rr1 = f(); // fine: bind rr1 to temporary X&& rr2 = a; // error: bind a is an lvalue
24-Nov-09 96
Rvalue reference: move semantics• Move assignment is more effective for
objects with resources. For strings s1=s2 – Copy Assignment
• makes a copy of s2's chars
– Move Assignment • lets s1 treat s2's chars as its own • deletes s1's old characters or • leaves them in s2, presumably to be destroyed
• How do we know whether it's ok to simply move from a source? We tell the compiler:
24-Nov-09 97
Rvalue reference: move semantics• move(x): “You can treat x as an rvalue". template<class T> void swap(T& a, T& b) // "perfect swap" (almost) {
T tmp = move(a); // could invalidate a a = move(b); // could invalidate b b = move(tmp); // could invalidate tmp
}
24-Nov-09 99
References1. ISO/IEC JTC1/SC22/WG21 - The C++ Standards Committee.
http://www.open-std.org/jtc1/sc22/wg21/ 2. C++0x FAQ: by Bjarne Stroustrup. www.research.att.com/~bs/C+
+0xFAQ.html3. C++0x Support in GCC: gcc.gnu.org/projects/cxx0x.html4. C++0x Support in Visual C++: Visual Studio 2010 Beta 2.
http://blogs.msdn.com/somasegar/archive/2009/10/19/announcing-visual-studio-2010-and-net-fx-4-beta-2.aspx (19-Oct-09)
5. C++0x. en.wikipedia.org/wiki/C++0x6. C++0x: The Dawning of a New Standard: (Aug-09)
www.devx.com/SpecialReports/Door/38865 - Overview: C++ Gets an Overhaul, Easier C++: An Introduction to Concepts, Simpler Multithreading in C++0x, The State of the Language: An Interview with Bjarne Stroustrup & Timeline: C++ in Retrospect:
7. C++0x - An Overview. http://csclub.uwaterloo.ca/media/C++0x%20-%20An%20Overview.html
24-Nov-09 100
Credit • Santanu Sinha
– Trying out examples in GCC
24-Nov-09 101
Thank You