2011-06-02 71 views
0

不应该从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的原因è?

+3

如果RVO正在阻止它,为什么你不想让它这样做? – 2011-06-02 02:27:35

+0

@John Zwinck:这个例子是人为设计 – 2011-06-03 00:24:22

回答

2

RVO启动并删除副本,并在p中构建GetPerson("X", 21)。复制构造函数和移动构造函数都不需要被调用。

如果你想在这里强制移动,那么std::move(GetPerson("X", 21))应该做的伎俩,但我不知道你为什么想。

1

移动构造函数是否被调用是不重要的。重要的是COPY构造函数不被调用。

如果你的代码依赖于在这里调用的移动构造函数,那么它将被破坏,根据[class.copy] p31。

+0

我打算编辑你的答案以包含§12.8/ 31的内容,但是好的主要是需要重新格式化很多文本。 – ildjarn 2011-06-02 16:45:32

相关问题