Perfect forwarding and c perfect forwarding

Source: Internet
Author: User

Perfect forwarding and c perfect forwarding

Perfect forwarding

#include <iostream>#include <string>#include <utility>using std::cout;using std::endl;using std::string;class  Name{public:    Name(const string & aName) :name{aName}    {        cout << "Lvalue Name constructor." << endl;    }    Name(string && aName) :name{ std::move(aName) }    {        cout << "Rvalue Name constructor." << endl;    }        const string & GetNmae()const    {        return name;    }private:    string name;};class Person{public:    template<typename T1,typename T2>    Person(T1 && first, T2 && second) :firstname{ std::forward<T1>(first) }, seondname{ std::forward<T2>(second) }    {        cout << "-------------------" << endl;    }    string getName()const    {        return firstname.GetNmae() + " " + seondname.GetNmae();    }private:    Name firstname;    Name seondname;};int main(){    Person me{ string{"Ivor"},string{"Horton"} };    cout << me.getName() << endl << endl;    string first{"Fred"};    string second{"Fernackerpan"};    Person other{first,second};    cout << other.getName()<< endl << endl;    Person brother{ first,string{"Bloggs"} };    cout << brother.getName() << endl << endl;    Person another{"Richard","Horton"};    cout << another.getName() << endl;}

Output result:

Rvalue Name constructor.
Rvalue Name constructor.
-------------------
Ivor Horton

Lvalue Name constructor.
Lvalue Name constructor.
-------------------
Fred Fernackerpan

Lvalue Name constructor.
Rvalue Name constructor.
-------------------
Fred Bloggs

Rvalue Name constructor.
Rvalue Name constructor.
-------------------
Richard Horton

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.