以下代码在下面(代码之后)生成编译器错误,但如果向量直接包含 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 &)'