GNU C++ extension implements compound literal differently form C99 in the sense that GNU C++ compound literal is a temporary object and has single-line life time.
So this code gives compile error trying to get the address of such a temporary object:
#include <iostream>
using namespace std;
#include <valarray>
int main() {
int n = 5;
std::valarray<int> arr((int[]){1,1,2,2,3}, n);
//^^^^^ error here, although the compound literal
// outlives the constructor
for (int i = 0; i < n; ++i)
cout << arr[i] << ' ';
cout << endl;
}
However, by changing (int[]){1,1,2,2,3}
to (const int[]){1,1,2,2,3}
, this error disappears and the code runs OK.
Then it seems that by adding const
qualifier the compound literal's is no longer a temporary.
I know that const
reference can increase the life time of temporary object to the life time of the reference, but I don't see how that is related to this question.
So my question is, is above code well defined behavior by C++ standard and/or GNU C++ extension?