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

解决方案

这看起来像是 std::lib 中的错误。我确信它之所以来到这里是因为历史的发展 vector 规格。

在 C++98/03 中 vector 有这个构造函数:

explicit vector(size_type n, const T& value = T(), const Allocator& = Allocator());

规格是 T 将默认构造一次,然后复制构造 n 使用默认后两个参数调用时的次数。

在 C++11 中,这被更改为:

explicit vector(size_type n);
vector(size_type n, const T& value, const Allocator& = Allocator());

第二个构造函数的规范没有改变。但第一个做到了:它应该默认构造 T n 次,并且根本不复制(或移动)它。

我本以为错误消息会说已删除或私有 复制构造函数unique_ptr 正在被使用。这本来表明 vector 遵循 C++98/03 规范,并且尚未更新。

但由于诊断抱怨 unique_ptr复制作业 相反,那么它看起来像 vector 已更新,但错误。听起来它正在使用 C++98/03 中的这个签名:

explicit vector(size_type n, const T& value = T(), const Allocator& = Allocator());

和默认构造 n T的,然后分配 value 对那些 n T的。

其他提示

您没有包含移动分配运算符,这是世代odicetagcode要求的一部分,只有一个移动构造函数。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top