Debian Codegraph @

libcxx/test/libcxx-03/input.output/iostreams.base/ios.base/ios.base.cons/dtor.uninitialized.pass.cpp

raw
1 //===----------------------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8
9 // TODO(mordante) Investigate
10 // UNSUPPORTED: apple-clang
11
12 // UNSUPPORTED: no-exceptions
13
14 // The fix for issue 57964 requires an updated dylib due to explicit
15 // instantiations. That means Apple backdeployment targets remain broken.
16 // XFAIL using-built-library-before-llvm-19
17
18 // <ios>
19
20 // class ios_base
21
22 // ~ios_base()
23 //
24 // Destroying a constructed ios_base object that has not been
25 // initialized by basic_ios::init is undefined behaviour. This can
26 // happen in practice, make sure the undefined behaviour is handled
27 // gracefully.
28 //
29 //
30 // [ios.base.cons]/1
31 //
32 // ios_base();
33 // Effects: Each ios_base member has an indeterminate value after construction.
34 // The object's members shall be initialized by calling basic_ios::init before
35 // the object's first use or before it is destroyed, whichever comes first;
36 // otherwise the behavior is undefined.
37 //
38 // [basic.ios.cons]/2
39 //
40 // basic_ios();
41 // Effects: Leaves its member objects uninitialized. The object shall be
42 // initialized by calling basic_ios::init before its first use or before it is
43 // destroyed, whichever comes first; otherwise the behavior is undefined.
44 //
45 // ostream and friends have a basic_ios virtual base.
46 // [class.base.init]/13
47 // In a non-delegating constructor, initialization proceeds in the
48 // following order:
49 // - First, and only for the constructor of the most derived class
50 // ([intro.object]), virtual base classes are initialized ...
51 //
52 // So in this example
53 // struct Foo : AlwaysThrows, std::ostream {
54 // Foo() : AlwaysThrows{}, std::ostream{nullptr} {}
55 // };
56 //
57 // Here
58 // - the ios_base object is constructed
59 // - the AlwaysThrows object is constructed and throws an exception
60 // - the AlwaysThrows object is destrodyed
61 // - the ios_base object is destroyed
62 //
63 // The ios_base object is destroyed before it has been initialized and runs
64 // into undefined behavior. By using __loc_ as a sentinel we can avoid
65 // accessing uninitialized memory in the destructor.
66
67 #include <ostream>
68
69 struct AlwaysThrows {
70 AlwaysThrows() { throw 1; }
71 };
72
73 struct Foo : AlwaysThrows, std::ostream {
74 Foo() : AlwaysThrows(), std::ostream(nullptr) {}
75 };
76
77 int main(int, char**) {
78 try {
79 Foo foo;
80 } catch (...) {
81 };
82 return 0;
83 }