【发布时间】:2012-07-26 17:36:17
【问题描述】:
以下代码会在下面(代码之后)生成编译器错误,但如果向量直接包含 unique_ptr 则不会(请参阅注释的代码行)。任何想法为什么?
问题更关心“#if 1”块中的代码块,“#else”块产生的错误(将“#if 1”改为“#if 0”后)类似,但是更值得期待。
// MoveSemantics.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <memory>
#include <vector>
typedef std::unique_ptr<int> upi;
struct S
{
S() : p(new int(123)) {}
S(S&& s) : p( std::move(s.p) ) {} // NB: the move constructor is supposed to be used? (but not)
upi p;
};
#if 1
void test()
{
//std::vector<S> vs; // Okay
//std::vector<upi> vupi(10); // Okay
std::vector<S> vs(10); // Error! why in the hell does the compiler want to generate a copy constructor here??
}
#else
void test()
{
std::vector<S> vs;
vs.push_back( S() );
const S& s = vs.front();
//S& s = vs.front(); // fine!
S s1 = std::move(s); // Error, but expected
}
#endif
int _tmain(int argc, _TCHAR* argv[])
{
return 0;
}
编译器错误:
1> error C2248: 'std::unique_ptr<_Ty>::operator =' : cannot access private member declared in class 'std::unique_ptr<_Ty>'
1> with
1> [
1> _Ty=int
1> ]
1> c:\program files\microsoft visual studio 11.0\vc\include\memory(1435) : see declaration of 'std::unique_ptr<_Ty>::operator ='
1> with
1> [
1> _Ty=int
1> ]
1> This diagnostic occurred in the compiler generated function 'S &S::operator =(const S &)'
【问题讨论】:
-
'S &S::operator =(const S &)'-- 编译器不会尝试在此处调用副本 constructor...向您的类添加移动赋值运算符。 -
Doh,这看起来像是一个疏忽!今天我的代码太多了!谢谢Xeo!我怎么能接受你的评论作为答案? :D
-
我仍然有点困惑,VS 需要赋值运算符 at all 用于
count构造函数。它不应该那样做。 -
没错!我基于公平的推理假设移动构造函数就足够了......
-
不仅如此,
count构造函数应该只是值构造(也称为默认构造)对象,甚至不移动任何东西......
标签: c++ visual-c++ vector c++11 unique-ptr