Created
April 25, 2015 12:20
-
-
Save beyondwdq/1e03dfadaecb9e27bbe0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <string> | |
#include <iostream> | |
#include <type_traits> | |
using namespace std; | |
class Person | |
{ | |
public: | |
Person(const std::string &name, int age) | |
: name_(name) | |
, age_(age) | |
{ | |
cout << "ctor " << this->name() << endl; | |
} | |
~Person() | |
{ | |
cout << "dtor " << name() << endl; | |
} | |
Person(const Person &other) | |
: name_(other.name_) | |
, age_(other.age_) | |
{ | |
cout << "copy ctor " << name() << endl; | |
} | |
Person(Person &&other) | |
: name_(std::move(other.name_)) | |
, age_(other.age_) | |
{ | |
cout << "move ctor " << name() << endl; | |
} | |
const std::string & name() const { return name_; } | |
int age() const { return age_; } | |
private: | |
std::string name_; | |
int age_; | |
}; | |
Person makePerson1(const std::string &name, int age) | |
{ | |
return Person(name, age); | |
} | |
Person &&makePerson2(const std::string &name, int age) | |
{ | |
return Person(name, age); | |
} | |
void printPerson(const Person &person) | |
{ | |
cout << person.name() << " at " << person.age() << endl; | |
} | |
int main(int argc, const char *argv[]) | |
{ | |
// find the error of the following code | |
Person p1 = makePerson1("Jone", 25); | |
printPerson(p1); | |
Person &p2 = makePerson1("Jack", 25); | |
printPerson(p2); | |
Person &&p3 = makePerson1("Rose", 25); | |
printPerson(p3); | |
//------------------------------ | |
auto p4 = makePerson2("Bob", 25); | |
cout << std::is_rvalue_reference<decltype(p4)>::value << endl; | |
printPerson(p4); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment