1
2 /*
3 * Copyright (C) 2019 The Android Open Source Project
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18 #include <vector>
19
20 #include "perfetto/ext/base/no_destructor.h"
21 #include "test/gtest_and_gmock.h"
22
23 namespace perfetto {
24 namespace base {
25 namespace {
26
27 class SetFlagOnDestruct {
28 public:
SetFlagOnDestruct(bool * flag)29 SetFlagOnDestruct(bool* flag) : flag_(flag) {}
~SetFlagOnDestruct()30 ~SetFlagOnDestruct() { *flag_ = true; }
31
32 bool* flag_;
33 };
34
TEST(NoDestructorTest,DoesNotDestruct)35 TEST(NoDestructorTest, DoesNotDestruct) {
36 bool destructor_called = false;
37 { SetFlagOnDestruct f(&destructor_called); }
38 ASSERT_TRUE(destructor_called);
39
40 // Not destructed when wrapped.
41 destructor_called = false;
42 { NoDestructor<SetFlagOnDestruct> f(&destructor_called); }
43 ASSERT_FALSE(destructor_called);
44 }
45
46 class NonTrivial {
47 public:
NonTrivial(std::vector<int> v,std::unique_ptr<int> p)48 NonTrivial(std::vector<int> v, std::unique_ptr<int> p)
49 : vec_(v), ptr_(std::move(p)) {}
50
51 std::vector<int> vec_;
52 std::unique_ptr<int> ptr_;
53 };
54
TEST(NoDestructorTest,ContainedObjectUsable)55 TEST(NoDestructorTest, ContainedObjectUsable) {
56 static NoDestructor<NonTrivial> x(std::vector<int>{1, 2, 3},
57 std::unique_ptr<int>(new int(42)));
58
59 ASSERT_THAT(x.ref().vec_, ::testing::ElementsAre(1, 2, 3));
60 ASSERT_EQ(*x.ref().ptr_, 42);
61
62 x.ref().vec_ = {4, 5, 6};
63 ASSERT_THAT(x.ref().vec_, ::testing::ElementsAre(4, 5, 6));
64 }
65
66 } // namespace
67 } // namespace base
68 } // namespace perfetto
69