Reputation: 1417
I have a constructor that takes a reference to an array as a parameter. Can I use a brace-enclosed initializer list to call that constructor?
Is the lifetime of the temporary array the lifetime of the constructor, or is that not guaranteed?
My main question:
Is the following example program correct?
class Test {
public:
template <size_t N>
Test(const int (&numbers)[N]) {
for (const int &number : numbers)
sum += number;
}
int getSum() const {
return sum;
}
private:
int sum = 0;
};
int main() {
Test test({1, 2, 3});
assert(test.getSum() == 6);
}
The code above works fine, however, the reason why I'm asking this is that I'm using the same approach in a larger project, where the elements of the array are not correctly initialized.
E.g. if {16}
is used as the argument to the constructor, sometimes the value of numbers[0]
is 0b00000000 00000000 00000000 00010000
, which is correct, and sometimes it is a different number, e.g. 0b11111111 11111111 11111111 00010000
or 0b00000000 00000000 00000011 00010000
.
The size of an int
is 4 bytes on the microcontroller platform I'm working on, and when numbers[0]
is wrong, I always see the same pattern: the least significant byte is correct, but in the 3 most significant bytes, there is always a block of all ones. This leads me to believe that it was not initialized correctly.
I haven't been able to isolate the problem or reproduce it using a small example.
Upvotes: 2
Views: 66
Reputation: 217398
In Test test({1, 2, 3});
, lifetime of the temporary array ends at ;
(so after the constructor call finished).
So your usage in constructor is correct.
But if you kept reference to that array as member, that reference would become dangling.
Upvotes: 2