如何初始化与删除,拷贝构造函数的类阵列(C ++ 11) [英] How to initialize array of classes with deleted copy constructor (C++11)

查看:232
本文介绍了如何初始化与删除,拷贝构造函数的类阵列(C ++ 11)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我不能初始化对象的数组,如果他们有私人拷贝构造函数?专指以C ++ 03。我从这个问题什么我试图做C ++ 03不允许知道,但我认为这应该是可能的C ++ 11

The existing question on Why can't I initialise an array of objects if they have private copy constructors? specifically refers to C++03. I know from that question that what I am trying to do is not allowed in C++03 but I thought that it should be possible in C++11

我有一个非移动类(称之为儿童),我需要另一个类的构造函数初始化子阵列(称之为父)。所谓不可移动我的意思是,一个孩子对象的地址有对象的生命周期内保持不变。什么是做到这一点的正确方法?

I have a non-movable class (call it Child) and I need to initialize an array of Child in the constructor of another class (call it Parent). By "non-movable" I mean that the address of a Child object has to remain the same during that object's lifetime. What is the correct way to do this?

使用C ++ 11我已经试过如下:

With C++11 I've tried the following:

class Child
{
public:
    Child (int x) {}
    ~Child () {}

    Child (const Child &) = delete;
};

class Parent
{
public:
    Parent () : children {{5}, {7}} {}

private:
    Child children[2];
};

这code编译罚款铿锵3.5.0,GCC却4.9.1抱怨,我尝试使用删除拷贝构造函数:

This code compiles fine with Clang 3.5.0, but GCC 4.9.1 complains that I am trying to use the deleted copy constructor:

test.cc: In constructor ‘Parent::Parent()’:
test.cc:13:35: error: use of deleted function ‘Child::Child(const Child&)’
     Parent () : children {{5}, {7}} {}
                                   ^
test.cc:7:5: note: declared here
     Child (const Child &) = delete;
     ^

我读过有关复制初始化和直接初始化之间的差值(这里和的here ,例如),我想避免调用通过直接初始化拷贝构造函数。我收到的语法错误?这是海湾合作委员会的错误吗?或者是什么,我试图做是不可能的?

I've read about the difference between copy-initialization and direct-initialization (here and here, for example), and I want to avoid calling the copy constructor by using direct-initialization. Am I getting the syntax wrong? Is this a bug in GCC? Or is what I am trying to do just not possible?

推荐答案

我同意,这似乎是一个错误的GCC(报道的 63707 )。

I agree with the comments that this seems to be a GCC bug (reported as 63707).

它只是无法编译时数组中的类型有一个用户定义的析构函数,这是没有道理给我。

It only fails to compile when the type in the array has a user-defined destructor, which doesn't make sense to me.

这篇关于如何初始化与删除,拷贝构造函数的类阵列(C ++ 11)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆