小编kcm*_*700的帖子

为什么对象生成器调用的r值引用需要复制构造函数?

我在使用Visual Studio 2010 C++时遇到以下代码问题.

makeA()只是C++中的一个对象生成器习惯用法(比如std :: make_pair)

#include <stdio.h>

struct A{ // 7th line
    A() {}
    A(A &&) {printf("move\n");}
    ~A() {printf("~A();\n");}
private:
    A(const A &) {printf("copy\n");} // 12th line
};

A makeA()
{
    return A();
}

int main()
{
    A &&rrefA(makeA()); // 22nd line
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

错误信息

2>d:\test.cpp(22): error C2248: 'A::A' : cannot access private member declared in class 'A'
2>          d:\test.cpp(12) : see declaration of 'A::A'
2>          d:\test.cpp(7) : see declaration of 'A'
2>
Run Code Online (Sandbox Code Playgroud)

我希望makeA()能同时调用A()构造函数和A(A &&)构造函数,并且第22行调用makeA()而不是其他任何东西.(如果没有RVO)编译器不应该要求A(const A&)构造函数可访问,对吗?

你能告诉我代码有什么问题吗? …

c++ visual-studio-2010 rvalue-reference visual-c++ c++11

8
推荐指数
1
解决办法
392
查看次数