Initialization order issues related to std::cout and inline variables
Jonathan Wakely
jwakely.gcc@gmail.com
Sat May 11 15:17:37 GMT 2024
On Sat, 11 May 2024, 10:43 Jan Schultke, <janschultke@googlemail.com> wrote:
> Hi, I've realized that according to the current wording in the
> standard, and with the current implementation in libstdc++, there is
> no reliable way to initialize std::cout before dynamic init of inline
> variables:
>
> > // included from <iostream>:
> > namespace std {
> > // ...
> > extern ostream cout;
> > // libstdc++ implementation detail; initializes cout:
> > static ios_base::Init __ioinit;
> > }
> >
> > // then, in our own code, possibly a header:
> > inline int x = [] {
> > std::cout << "awoo"; // possibly UB
> > return 0;
> > }();
>
> It would be fine if std::cout was inline, and it would be fine if x
> was non-inline, but only x being inline makes its initialization
> indeterminately sequenced, even if <iostream> is always included prior
> to wherever x is defined. This is very strange, and I think we should
> do something about it.
>
> - Is this a known issue in the committee?
I don't think I've seen it discussed.
Is this defect-worthy?
>
Probably yes.
- Could we make std::cout inline without breaking anything so that
> this would become valid?
>
No, I don't think so.
The constructor of cout doesn't do anything, it's the ios::Init constructor
that initializes things. That has an init priority attribute, so I'd be
surprised if the inline variable gets created first when using libstdc++.
That seems like a bug if it does.
> See https://stackoverflow.com/q/78463564/5740428 for someone running
> into an issue with this (using clang, not GCC), and see the answer in
> that Q&A for an in-depth explanation of wording and why this happens.
>
Your explanation seems based on older versions of libstdc++, as we don't
have an ios::Init object there now. There's only one stuck object,
initialized inside libstdc++.so when that's loaded.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://gcc.gnu.org/pipermail/libstdc++/attachments/20240511/17128768/attachment.htm>
More information about the Libstdc++
mailing list