I am using C++11 and I want to initialize an array of objects in the initializer list of a constructor. I have found a related question but it doesn't meet my needs:
- I would like the class of the objects of the array to be non-copyable.
- I would like the class of the objects of the array to have a destructor.
Compiles:
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;
};
Doesn't compile:
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 am using g++ and get the following errors:
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
Why does it make a difference if the object is non-copyable?
Aucun commentaire:
Enregistrer un commentaire