2014年7月28日 星期一

lvalue & rvalue

reference:
http://www.cprogramming.com/c++11/rvalue-references-and-move-semantics-in-c++11.html
http://en.cppreference.com/w/cpp/language/value_category

An lvalue is an expression whose address can be taken

 You can make assignments to lvalues



1
2
3
4
5
6
7
int x;
int& getRef ()
{
        return x;
}
getRef() = 4;

A Rvalue is a temporary value.

You can't make assignments to lvalues


1
2
3
4
5
string getName ()
{
    return "Alex";
}
getName();



C++11 rvalue reference
let you bind a mutable reference to an rvalue
Rvalue references use the && syntax instead of just &, and can be const and non-const

1
2
const string&& name = getName(); // ok
string&& name = getName(); // also ok - praise be!

1
2
3
4
5
6
7
8
9
printReference (const String& str)
{
        cout << str;
}
printReference (String&& str)
{
        cout << str;
}

1
2
3
4
string me( "alex" );
printReference( me ); // calls the first printReference function, taking an lvalue reference
printReference( getName() ); // calls the second printReference function, taking a mutable rvalue reference


xvalue

An xvalue is an expression that identifies an "eXpiring" object, that is, the object that may be moved from. 

std::move

std::move obtains an rvalue reference to its argument and converts it to an xvalue.


std::make_unique

Constructs an object of type T and wraps it in a std::unique_ptr.

std::unique_ptr

std::unique_ptr is a smart pointer that retains sole ownership of an object through a pointer and destroys that object when the unique_ptr goes out of scope.
No two unique_ptr instances can manage the same object.

Example

#include <iostream>
#include <memory>
 
struct Foo
{
    Foo()      { std::cout << "Foo::Foo\n";  }
    ~Foo()     { std::cout << "Foo::~Foo\n"; }
    void bar() { std::cout << "Foo::bar\n";  }
};
 
void f(const Foo &)
{
    std::cout << "f(const Foo&)\n";
}
 
int main()
{
    std::unique_ptr<Foo> p1(new Foo);  // p1 owns Foo
    if (p1) p1->bar();
 
    {
        std::unique_ptr<Foo> p2(std::move(p1));  // now p2 owns Foo
        f(*p2);
 
        p1 = std::move(p2);  // ownership returns to p1
        std::cout << "destroying p2...\n";
    }
 
    if (p1) p1->bar();
 
    // Foo instance is destroyed when p1 goes out of scope
}
Output:
Foo::Foo
Foo::bar
f(const Foo&)
destroying p2...
Foo::bar
Foo::~Foo

沒有留言:

張貼留言