Suppose the struct is supplied with two template arguments, one being typename T and the other one being size_t N. Now, that struct should store a static array of element type T and size N. In some cases, it might be fine to initialize the array with default values upon creation of an instance, which is what I think happens anyway if you have something like
template<typename T, size_t N>
struct Foo {
T values[N];
size_t size;
explicit Foo(size_t _size) : size{ _size } {}
}
So, as said, I think the behaviour in this case is that values just automatically gets initialized with default values (calling the default constructor of T). But what if I want to pass some values for the array when constructing an object? The goal here is that I am able to pass a static array to the constructor and let that static array take the place of values. And ideally, there would be only two array creations in the whole procedure. But is that even possible? Consider the following example:
template<typename T, size_t N>
struct Foo {
T values[N];
size_t size;
explicit Foo(T _values[N], size_t _size) : values{ _values }, size{ _size} {}
}
Now, apart from me not even knowing if the above would work as expected, I am still a bit unsure about when copies happen in C++. I'd imagine that in the worst case, there would be 4 arrays created when calling the constructor of Foo:
- To call the constructor of
Foo, you need to pass an array, so you need to create that beforehand. - The constructor parameter
_valuesis pass-by-value, so a copy is happening here. - Before the constructor initializes any values, the static array is already initialized (?)
- When assigning
_valuestovalues, another copy is happening (?)
Now as said I'm really not sure about the copying behaviours in C++. Of course, we can rule out one array creation by making the _values parameter pass-by-reference. But still, the static array values would be initialized before being overwritten by _values, or so I think.
My question, therefore, is: What is the best strategy here? How do I have to write the code so that I trigger the least amount of array creations?
Thanks!
Edit:
No, I cannot use std::vector or any other data structure from the stdlib. And even if I could, my question is still about the best strategy for raw arrays, and not how to switch out my approach in favour of some wrapper.