Apr 26, 2014

[C++11] RVO


#include <iostream>

// print out 1 3 1

struct X {
X(const char *) { std::cout << 1; }
X(const X &) { std::cout << 2; }
X(X &&) { std::cout << 3; }
};

X f(X a) {
   return a; // no RVO due to 'a' is argument which construct inplace with parameter "hello"
             // always needs a copy constructor to copy 'a' to the extra tmp returned argument 'X'
}


X g(const char * b) {
   X c(b); //NRVO
   return c;
}

int main() {
   f("hello");
   g("hello");
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.