Instantiate const array reference as constructor parameter using initializer list, allowed or not?

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


Instantiate const array reference as constructor parameter using initializer list, allowed or not?



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.


{16}


numbers[0]


0b00000000 00000000 00000000 00010000


0b11111111 11111111 11111111 00010000


0b00000000 00000000 00000011 00010000


int


numbers[0]



I haven't been able to isolate the problem or reproduce it using a small example.









By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

How to scale/resize CVPixelBufferRef in objective C, iOS

Stripe::AuthenticationError No API key provided. Set your API key using “Stripe.api_key = ”

SVG with two text elements. When one resizes due to textLength - how to resize the other one to the same character size