不應該從GetPerson的未命名的返回值綁定到移動構造函數嗎?爲什麼移動構造函數在這個人爲的例子中不被調用?
person.hpp
#ifndef PERSON_H
#define PERSON_H
#include <string>
struct Person {
Person(std::string name, int age) : name(name), age(age) {
std::cout << "ctor" << std::endl;
}
Person(const Person& rhs) : name(rhs.name), age(rhs.age) {
std::cout << "copy ctor" << std::endl;
}
Person(Person&& rhs) : name(std::move(rhs.name)), age(std::move(rhs.age)) {
std::cout << "move ctor" << std::endl;
}
~Person() {
std::cout << "dtor" << std::endl;
}
std::string name;
int age;
};
#endif
的main.cpp
#include <iostream>
#include "person.hpp"
Person GetPerson(std::string name, int age) {
return Person(name, age);
}
int main(int argc, char* argv[]) {
Person p(GetPerson("X", 21));
}
我用gcc 4.4.3版(Ubuntu的4.4.3-4ubuntu5),並編譯:
gcc -g -x c++ -lstdc++ -std=c++0x -o main ./main.cpp
是RVO還是NRVO的原因è?
如果RVO正在阻止它,爲什麼你不想讓它這樣做? – 2011-06-02 02:27:35
@John Zwinck:這個例子是人爲設計 – 2011-06-03 00:24:22