PDF
1C++NRVOContents ..................................................................................... 1 ............................................................................. 2NRVO ............................................................................................ 2#include <iostream>using namespace std;class Value { public: Value(int _m):m(_m) { std::cout << "test constructor" << m << std::endl; } Value(const Value& t) { std::cout << "test copy constructor" << m << std::endl; this->m = t.m; } ~Value() { std::cout << "test destructor" << m << std::endl; } void print() { std::cout << "m:" << m << std::endl; } private: int m;};class Producer {public: Value produce(int i) { Value t(i); return t; }};int main(int argc, char* argv[]) { std::cout << "Hello world!" << std::endl; Producer p; Value t = p.produce(100); t.print(); return 1;} NRVO2Hello world!test constructor100m:100test destructor100便class Producer {public: Value* produce(int i){ Value t(i); return &t; }};test.cpp:21:17: warning: address of stack memory associated with local variable 't' returned [-Wreturn-stack-address] return &t; ^1 warning generated.Hello world!test constructor100test destructor100m:-327065280NRVOhfli@CNhfli ~ $ g++ -fno-elide-constructors test.cpphfli@CNhfli ~ $ ./a.outHello world!test constructor100test copy constructor0test destructor100test copy constructor0test destructor100 NRVO3m:100test destructor100

HTML view coming soon.

Download PDF for the full formatted version.