如何使用已删除的复制构造函数初始化类数组 (C++11) [英] How to initialize array of classes with deleted copy constructor (C++11)

查看:22
本文介绍了如何使用已删除的复制构造函数初始化类数组 (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

我有一个不可移动的类(称之为 Child),我需要在另一个类的构造函数中初始化一个 Child 数组(称之为 Parent).不可移动"是指子对象的地址在该对象的生命周期内必须保持不变.这样做的正确方法是什么?

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];
};

此代码在 Clang 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;
     ^

我已经阅读了复制初始化和直接初始化之间的区别(此处此处,例如),我想避免使用直接初始化来调用复制构造函数.我的语法错误吗?这是 GCC 中的错误吗?或者我正在尝试做的事情是不可能的?

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天全站免登陆