Last active
August 29, 2015 14:21
-
-
Save tetsuok/18384fbd065333d714dd to your computer and use it in GitHub Desktop.
NRVO
This file contains 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 <iostream> | |
class A { | |
public: | |
A() {} | |
~A() { std::cout << "destructed" << std::endl; } | |
A(const A&) { | |
std::cout << "copy" << std::endl; | |
} | |
A(A&&) { | |
std::cout << "move" << std::endl; | |
} | |
A& operator=(const A&) { | |
std::cout << "copy assignment" << std::endl; | |
return *this; | |
} | |
static A create() { | |
return A(); | |
} | |
static A create_named() { | |
A a; | |
return a; | |
} | |
}; | |
class B { | |
public: | |
B(A a) : a_(a) {} | |
~B() { | |
std::cout << "B: destructed" << std::endl; | |
} | |
private: | |
A a_; | |
}; | |
int main() { | |
{ | |
const auto a = A::create(); | |
} | |
{ | |
const auto a = A::create_named(); | |
} | |
return 0; | |
} |
This file contains 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 <utility> | |
#include <iostream> | |
#include <string> | |
class A { | |
public: | |
A() : name_("hello") {} | |
~A() { std::cout << "destructed" << std::endl; } | |
A(const A& o) { | |
std::cout << "copy" << std::endl; | |
name_ = o.name_; | |
} | |
A(A&& o) { | |
std::cout << "move" << std::endl; | |
name_ = std::move(o.name_); | |
} | |
A& operator=(const A& o) { | |
std::cout << "copy assignment" << std::endl; | |
name_ = o.name_; | |
return *this; | |
} | |
static A create() { return A(); } | |
static A create_named() { | |
A a; | |
return a; | |
} | |
std::string name() const { return name_; } | |
private: | |
std::string name_; | |
}; | |
class B { | |
public: | |
B(A a) : a_(std::move(a)) {} | |
static B create() { return B(A::create()); } | |
// NRVO? | |
static B create_named() { | |
auto a = A::create(); | |
// return B(a); // copy will occur | |
return B(std::move(a)); // fix | |
} | |
std::string name() const { return a_.name(); } | |
private: | |
A a_; | |
}; | |
int main() { | |
{ | |
const auto b = B::create(); | |
std::cout << b.name() << std::endl; | |
} | |
{ | |
const auto b = B::create_named(); | |
std::cout << b.name() << std::endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment