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

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