数组的 C++ 构造函数初始值设定项

标签 c++ c++11 constructor initializer-list

我正在使用 C++11,我想在构造函数的初始化列表中初始化一个对象数组。我找到了一个相关的问题,但它不符合我的需求:

  • 我希望数组对象的类是不可复制的。
  • 我希望数组对象的类有一个析构函数。

编译:

class foo {
  public:
    foo(int& n) : i(n) {}
    //~foo() {} // If uncommented, it doesn't compile.

  private:
    int& i;

    // Disable copy constructor and assignment operator.
    foo(const foo&) = delete;
    foo& operator=(const foo&) = delete;
};

class bar {
  public:
    bar()
      : f{{i}, {i}}
    {
    }

  private:
    foo f[2];
    int i;
};

不编译:

class foo {
  public:
    foo(int& n) : i(n) {}
    ~foo() {} // If uncommented, it doesn't compile.


  private:
    int& i;

    // Disable copy constructor and assignment operator.
    foo(const foo&) = delete; // If commented out, it compiles.
    foo& operator=(const foo&) = delete;
};

class bar {
  public:
    bar()
      : f{{i}, {i}}
    {
    }

  private:
    foo f[2];
    int i;
};

我正在使用 g++ 并收到以下错误:

main.cpp: In constructor ‘bar::bar()’:
main.cpp:10:5: error: ‘foo::foo(const foo&)’ is private
main.cpp:17:19: error: within this context
main.cpp:17:19: error: use of deleted function ‘foo::foo(const foo&)’
main.cpp:10:5: error: declared here

如果对象是不可复制的,为什么会有所不同?

最佳答案

这是一个已知的 GCC 错误 63707状态为 NEW。相同的代码在 CLANG 中运行良好.

关于数组的 C++ 构造函数初始值设定项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34108250/

相关文章:

C++11 从 int& 和 long 的算术运算中自动推导类型

c++ - 直接和复制构造函数

c++ - "No source available for SSL_CTX_load_verify_locations()"使用 OpenSSL

c++ - 为什么qjsonvalue todouble转换会导致数据丢失?

C++ - 对齐内存

c++ - 谁能解释一下这个 C++ 程序。结果很奇怪 :(

c++ - 关于 Boost Signals2,没有名为 'apply' 的类模板

regex - Linux下c++ 11中正则表达式的奇怪行为

java - JFrame 构造函数的最佳实践?

java - 在不知道类名的情况下调用构造函数(java)