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?
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];
};
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;
^
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?
Can copy constructor be used to initialize one class object with another class object? Explanation: The restriction for copy constructor is that it must be used with the object of same class. Even if the classes are exactly same the constructor won't be able to access all the members of another class.
1. The copy constructor is used to initialize the members of a newly created object by copying the members of an already existing object. 2. Copy constructor takes a reference to an object of the same class as an argument.
Arrays can be created using a constructor with a single number parameter.
The copy constructor and copy-assignment operator are public but deleted. It is a compile-time error to define or call a deleted function. The intent is clear to anyone who understands =default and =delete . You don't have to understand the rules for automatic generation of special member functions.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With