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是原因吗?
答案 0 :(得分:2)
RVO启动并删除副本,并在GetPerson("X", 21)
中构建p
。无需复制构造函数和移动构造函数。
如果你想在这里强行迁移,那么std::move(GetPerson("X", 21))
应该可以解决问题,但我不确定你为什么要这样做。
答案 1 :(得分:1)
是否调用移动构造函数并不重要。重要的是不调用COPY构造函数。
如果您的代码依赖于此处调用的移动构造函数,那么它会被破坏,符合[class.copy]
p31。