c++ - vc++ 2010/2012:包含 unique_ptr 的结构的 std::vector 编译器错误

标签 c++ visual-c++ vector c++11 unique-ptr

以下代码会生成下面的编译器错误(在代码之后),但如果 vector 直接包含 unique_ptr,则不会生成编译器错误(请参阅注释的代码行)。有什么想法吗?

问题更关心“#if 1” block 中的代码块,“#else” block 生成类似的错误(在将“#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 的已删除或私有(private)复制构造函数。这表明 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 的。

关于c++ - vc++ 2010/2012:包含 unique_ptr 的结构的 std::vector 编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11697994/

相关文章:

arrays - Haskell Data.Vector.Storable.unsafeFromForeignPtr 与 C 结构指针/数组字段

java - C/C++ (dll) 与 JAVA (JAR) 中的动态链接

c++ - 如何对使用 Linux 的 GCC 创建的共享对象文件进行版本控制

c++ - 检查内联函数中的变量值

c++ - 图形编程

windows - _USING_V110_SDK71_ 未从 VC++ 2015、v140_xp、Release 中的默认值继承?

c++ - 在类中使用全局变量作为数组大小

c++ - `std::common_type` 是关联的吗?

c++ - 访问 C++ vector 中超出大小的元素

string - matlab 字符串向量/数组处理(乘法 u 和 str2num)