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 {
24 public: CMyClass();
25 public: CMyClass(const CMyClass& iOther);
26 public: ~CMyClass();
27
28 private: int fMagicValue;
29
30 private: static int kStartedConstructionMagicValue;
31 private: static int kFinishedConstructionMagicValue;
32};
33
34// Value for fMagicValue when the constructor has started running, but not yet finished
35int CMyClass::kStartedConstructionMagicValue = 0;
36// Value for fMagicValue when the constructor has finished running
37int CMyClass::kFinishedConstructionMagicValue = 12345;
38
39CMyClass::CMyClass() :
40 fMagicValue(kStartedConstructionMagicValue)
41{
42 // Signal that the constructor has finished running
43 fMagicValue = kFinishedConstructionMagicValue;
44}
45
46CMyClass::CMyClass(const CMyClass& /*iOther*/) :
47 fMagicValue(kStartedConstructionMagicValue)
48{
49 // If requested, throw an exception _before_ setting fMagicValue to kFinishedConstructionMagicValue
50 if (gCopyConstructorShouldThrow) {
51 throw std::exception();
52 }
53 // Signal that the constructor has finished running
54 fMagicValue = kFinishedConstructionMagicValue;
55}
56
57CMyClass::~CMyClass() {
58 // Only instances for which the constructor has finished running should be destructed
59 assert(fMagicValue == kFinishedConstructionMagicValue);
60}
61
62int main(int, char**)
63{
64 CMyClass instance;
65 std::list<CMyClass> vec;
66
67 vec.push_back(x: instance);
68
69 gCopyConstructorShouldThrow = true;
70 try {
71 vec.push_back(x: instance);
72 }
73 catch (...) {
74 }
75
76 return 0;
77}
78

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