C++11--move/forward

Source: Internet
Author: User

Std::move

Std::move () is provided in c++11 to convert the Lvalue to the right value, making it easy to use move semantics. Move is to transfer the state or ownership of an object from one object to another, only to transfer, without a memory copy.
All containers in C + + implement the move semantics, allowing us to optimize performance. Move simply shifts the control of the resource, essentially casting the lvalue to an rvalue reference to use the move semantics to avoid a meaningless copy of the object containing the resource. Move is valid for objects that have the shape of a member of a resource such as memory, file handle, and so on. If there are some basic types, such as an int or char[10] array, if you use Move, the copy will still occur (because there is no corresponding move constructor), so move is more meaningful for objects with resources.

    Std::list<std::string> tokens;    std::list<std::string> t = std::move (tokens); A move construct has occurred. When the list is implemented, it assigns the resource handle of the destination object to the resource handle of the source object, and the resource handle of the source object is emptied.

Std::forward

An rvalue reference type is independent of the value, an rvalue reference parameter acts as a formal parameter of the function, and when the parameter is forwarded inside the function it becomes an lvalue, not his original type.

If we need a way to forward to another function according to the original type of the parameter, this type of forwarding is called perfect forwarding .

Template<typename t>void Print (t& T) {    cout << "Lvalue" << Endl;} Template<typename t>void Print (t&& T) {    cout << "rvalue" << Endl;} Template<typename t>void Testforward (T && v) {    print (v);    Print (std::forward<t> (v));    Print (Std::move (v));} int main () {    testforward (1);    int x = 1;    Testforward (x);    Testforward (std::forward<int> (x));    return 0;}

C++11--move/forward

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.