Possible miscompile with std::initializer_list after r274385
| Bugzilla Link | 40562 |
| Version | trunk |
| OS | All |
| CC | @DougGregor,@nzaghen,@zygoloid |
Extended Description
Testcase is this (also found at https://godbolt.org/z/iO4IL7 )
#include <initializer_list>
class T {
public:
int c;
T(int c) : c(c) {}
};
extern void f(std::initializer_list<T>&);
void test() {
T t(666);
std::initializer_list<T> a({t});
//std::initializer_list<T> a{{t}};
f(a);
}
Something to note is that using the commented out version will work fine. I think both versions should be OK as "t" will still be live until the end of the scope.
The issue is that the initializer list will contain one element once we go into the function call, but the element won't actually exist. This leads to accessing uninitialized memory.
-O2 is needed to reproduce
Aaron Ballman — 03/18/2024 6:07 PM Hmm, it's a monday morning so take this with a grain of salt, but I think {t} is constructing a T via copy construction, which then gets materialized into a std::initializer_list, which then does move construction to a second std::initializer_list that is a. So I think this is a dangling reference to the backing array for the temporary initializer list.
Yeah, the AST we generate looks like my guess (and we issue a -Wdangling diagnostic, too): https://godbolt.org/z/6q9e9dYbj
I think std::initializer_list
mhappy — 03/18/2024 10:36 PM yeah, it's dangling reference and clang correctly provides diagnostic for it. But GCC handles it without dangling reference, clang should extend the lifetime of temporary being created here to the lifetime of a. "The backing array has the same lifetime as any other temporary object ([class.temporary]), except that initializing an initializer_list object from the array extends the lifetime of the array exactly like binding a reference to a temporary."
Aaron Ballman — 03/18/2024 10:47 PM Hmmm, you might be correct. The extended lifetime for the inner initializer_list should still be fine because that is moved into the outer initializer_list... mhappy — 03/18/2024 10:51 PM Thank You. I'll start working on this. Aaron Ballman — 03/18/2024 10:52 PM you may want to double-check this understanding though, CC @Vlad Serebrennikov (it may be a while before you get a response as folks are away at C++ standards meetings this week)
@Endilll Can you please give your thoughts on this. Thank You.
Note if we make a constexpr version: https://godbolt.org/z/qjfP6vKa4
Implementation reject the initialization.