C ++ constructor initializer for arrays

I am using C ++ 11 and I want to initialize an array of objects in the constructor initializer list. I found a related question, but it does not meet my needs:

  • I would like the array feature class not to be copied.
  • I would like the array feature class to have a destructor.

Collects:

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

Not compiling:

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

I use g ++ and get the following errors:

main.cpp: In constructorbar::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 functionfoo::foo(const foo&)’
main.cpp:10:5: error: declared here

Why does it matter if the object is not copied?

+4
source share
1 answer

This is a known GCC 63707 error with status NEW. The same code works fine in CLANG .

+2
source

Source: https://habr.com/ru/post/1618717/


All Articles