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// UNSUPPORTED: no-exceptions
10// <list>
11
12// void push_back(const value_type& x);
13
14#include <list>
15#include <cassert>
16#include <exception>
17
18#include "test_macros.h"
19
20// Flag that makes the copy constructor for CMyClass throw an exception
21static bool gCopyConstructorShouldThrow = false;
22
23class CMyClass {
24public:
25 CMyClass();
26
27public:
28 CMyClass(const CMyClass& iOther);
29
30public:
31 ~CMyClass();
32
33private:
34 int fMagicValue;
35
36private:
37 static int kStartedConstructionMagicValue;
38
39private:
40 static int kFinishedConstructionMagicValue;
41};
42
43// Value for fMagicValue when the constructor has started running, but not yet finished
44int CMyClass::kStartedConstructionMagicValue = 0;
45// Value for fMagicValue when the constructor has finished running
46int CMyClass::kFinishedConstructionMagicValue = 12345;
47
48CMyClass::CMyClass() : fMagicValue(kStartedConstructionMagicValue) {
49 // Signal that the constructor has finished running
50 fMagicValue = kFinishedConstructionMagicValue;
51}
52
53CMyClass::CMyClass(const CMyClass& /*iOther*/) : fMagicValue(kStartedConstructionMagicValue) {
54 // If requested, throw an exception _before_ setting fMagicValue to kFinishedConstructionMagicValue
55 if (gCopyConstructorShouldThrow) {
56 throw std::exception();
57 }
58 // Signal that the constructor has finished running
59 fMagicValue = kFinishedConstructionMagicValue;
60}
61
62CMyClass::~CMyClass() {
63 // Only instances for which the constructor has finished running should be destructed
64 assert(fMagicValue == kFinishedConstructionMagicValue);
65}
66
67int main(int, char**) {
68 CMyClass instance;
69 std::list<CMyClass> vec;
70
71 vec.push_back(x: instance);
72
73 gCopyConstructorShouldThrow = true;
74 try {
75 vec.push_back(x: instance);
76 } catch (...) {
77 }
78
79 return 0;
80}
81

source code of libcxx/test/std/containers/sequences/list/list.modifiers/push_back_exception_safety.pass.cpp