为什么is_copy_constructible在MSVC12中对unique_ptr返回true

时间:2015-12-07 14:01:27

标签: c++ c++11 typetraits msvc12

我原本期望这个静态断言开火:

#include <type_traits>
#include <memory>

int main() {
  static_assert(std::is_copy_constructible<std::unique_ptr<int>>::value, "UPtr has copy constructor?");
}

但事实并非如此。

使用MSVC12编译:

  

Microsoft(R)C / C ++优化编译器版本18.00.31101(适用于x64)

2 个答案:

答案 0 :(得分:15)

static_assert应该触发,std::unique_ptr有一个隐式删除的拷贝构造函数,所以这是一个bug。这看起来与此错误报告std::is_copy_constructible is broken

有关
  

(1)对于已删除的类型,std :: is_copy_constructible返回true   复制构造函数。

     

(2)对于组成的类型,std :: is_copy_constructible返回true   不可复制的类型。

并且回复是:

  

感谢您报告此错误。我们已修复它,修复程序将在2013年后的Visual Studio的下一个主要版本中提供。

另外,请参阅此错误报告:std::is_copy_constructible doesn't work correctly

请注意,断言在使用最新版Visual Studio的webcompiler上触发。最后一次更新是在Dec 3, 2015。断言也会触发clang( see it live )和gcc。

我发现了一个错误报告:A strange behavior of std::is_copy_constructible与您的代码非常相似:

static_assert(std::is_copy_constructible<std::unique_ptr<int>>::value, "");

有回应:

  

感谢您报告此错误。我们已经修好了,解决了   在VS 2015 Preview中可用。

不清楚,修复了哪个版本的Visual Studio。一个回复说2013年末版本,而后一个版本说2015预览。

答案 1 :(得分:0)

以下是使类不可复制的四种方法:

#include <stdio.h>
#include <type_traits>

class A {
public:
    A(const A&) = delete;
    void operator=(const A&) = delete;
};

class B {
private:
    B(const B&) = delete;
    void operator=(const B&) = delete;
};

class C {
public:
    C(const C&) = delete;
    void operator=(const C&) = delete;
    void operator=(C) = delete;
};

class D {
private:
    D(const D&) = delete;
    void operator=(const D&) = delete;
    void operator=(D) = delete;
};

int main() {
    printf("%d %d\n", std::is_copy_constructible<A>::value, std::is_copy_assignable<A>::value);
    printf("%d %d\n", std::is_copy_constructible<B>::value, std::is_copy_assignable<B>::value);
    printf("%d %d\n", std::is_copy_constructible<C>::value, std::is_copy_assignable<C>::value);
    printf("%d %d\n", std::is_copy_constructible<D>::value, std::is_copy_assignable<D>::value);
}

在MSVC2013 x64(18.00.40629 for x64)上,它会打印:

1 1    //A
0 1    //B
1 0    //C
0 0    //D

在正确的编译器上,所有八个值必须为零。

不幸的是,提供了一种解决MSVC2013中的错误的好方法,即使对于您自己的类也是如此。因为如果声明赋值运算符按值接受参数,则不能在同一个类中声明移动赋值(由于模糊的重载,任何移动赋值都不会编译)。

P.S。修复作业的关键思路来自this related answer