Reputation: 25613
I run into trouble if I would create an array of objects like this:
SM sc[8]{{0},{1},{2},{3},{4},{5},{6},{7}};
The constructor for SM is defined as:
SM::SM(int);
Because in c++ Each member is copy-initialized from the corresponding initializer-clause.
is given, I have a unsolved problem.
I already read:
Move Constructors and Static Arrays
Initialization of member array objects avoiding move constructor
Move constructor is required even if it is not used. Why?
constexpr array of constexpr objects using move ctor
Yes, all the answers describing very well what is giong on with list initialization but I could not found an idea how to get a static array of objects now.
Is there any work around for that problem? Creating a array of pointers and do a runtime initialization with new or new@ operation requires a lot more runtime a memory space. It is a bit problematic because I am on a AVR 8 bit controller.
Upvotes: 1
Views: 251
Reputation: 72401
"copy-initialized" does not mean "calls a copy constructor."
C++14 8.5/15:
The initialization that occurs in the form
T x = a;
as well as in argument passing, function return, throwing an exception, handling an exception, and aggregate member initialization is called copy-initialization.
Note that an initializer and an initialized object can have different types.
So you can use an initializer list to initialize an array without necessarily invoking any copy constructor.
Upvotes: 1
Reputation: 9093
Just some feedback, in an answer due to code snippets:
Adapting the code at the 3rd link to:
#include <iostream>
using namespace std;
struct SM {
int val;
SM(int a) : val(a) { cout <<"Constructor val="<<a<<endl;}
~SM() { cout << "Destructor val="<<val<<endl; }
SM(const SM& ) = delete;
SM(SM&& ) = delete;
};
int main()
{
SM sc[8] = { {0},{1},{2},{3},{4},{5},{6},{7} };
return 0;
}
compiling with
g++ -std=c++11
and running, results in:
Constructor val=0
Constructor val=1
Constructor val=2
Constructor val=3
Constructor val=4
Constructor val=5
Constructor val=6
Constructor val=7
Destructor val=7
Destructor val=6
Destructor val=5
Destructor val=4
Destructor val=3
Destructor val=2
Destructor val=1
Destructor val=0
What exactly is the trouble?
Upvotes: 3