c++ - 删除类的复制构造函数时初始化类的数组成员

标签 c++ visual-c++ visual-c++-2015

这是我正在处理的用例的较小版本。

#include <mutex>
template<typename T = float>
class Foo
{
public:
    Foo(int x, int y):m_mutex(){}
private:
    std::mutex  m_mutex; // This is must have in my project
};

typedef Foo<float> Foo_typedef;

class Func
{
public:     
    static Foo_typedef static_array[2];
};

Foo_typedef Func::static_array[2] = { Foo_typedef(2,3), Foo_typedef(2,3) };

int main()
{   
    return 0;
}

编译此 VS 2015 Update 2 后发出以下错误。

error C2280: 'Foo<float>::Foo(const Foo<float> &)': attempting to reference a deleted function
note: see declaration of 'Foo<float>::Foo'

我环顾四周,我怀疑这可能是两个原因之一。

1) std::mutex 的复制构造函数成员被删除

2) This我认为这可能与我所看到的相似。

是哪一个?我该怎么做才能绕过 VS 2015 Update 2 编译器抛出的这个错误?

更新:更新了构造函数,它接受一些需要传递给Foo_typedef的参数。

最佳答案

您需要使用构造函数就地构造元素:

Foo_typedef Func::static_array[2] = { {2, 3}, {2, 3} };

有了这个,就没有复制或移动,因为这两个元素是就地构造的。

标准说(§8.5.1/2 [dcl.init.aggr],重点是我的):

When an aggregate is initialized by an initializer list, [...] the elements of the initializer list are taken as initializers for the members of the aggregate [...].

在您的情况下,这意味着 Foo_typedef(2,3) 将被视为您的 Foo_typedef初始化程序,因此是一个拷贝将需要。在我给出的代码中,{2, 3} 将被视为一个初始化程序,并且将调用相应的构造函数(无拷贝)。

关于c++ - 删除类的复制构造函数时初始化类的数组成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37298365/

相关文章:

c++ - range-v3 如何操作::使用定界符加入

c++ - 透明度分层窗口白色

c++ - 数组维度的变化导致 C++ 崩溃

c++ - 如果我没有为指针分配新值,是否需要删除它?

mysql - 使用IP地址连接到MySql

c++ - std::set 为什么比 std::map 慢?

c++ - C++ : Cannot I assign values to a variable in header file?

c++ - MSVC : "use of class template requires template argument list" inside STL containers

c++ - MSVC 与 GCC 与 sizeof 的行为不一致