1 /*
2  * Copyright (C) 2017 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "perfetto/ext/base/weak_ptr.h"
18 
19 #include "test/gtest_and_gmock.h"
20 
21 namespace perfetto {
22 namespace base {
23 namespace {
24 
25 class WeakClass {
26  public:
WeakClass()27   WeakClass() : weak_factory(this) {}
28   WeakPtrFactory<WeakClass> weak_factory;
29 };
30 
TEST(WeakPtrTest,AllCases)31 TEST(WeakPtrTest, AllCases) {
32   std::unique_ptr<WeakClass> owned_instance(new WeakClass());
33   WeakPtr<WeakClass> weak_ptr1 = owned_instance->weak_factory.GetWeakPtr();
34   WeakPtr<WeakClass> weak_ptr2;
35   weak_ptr2 = owned_instance->weak_factory.GetWeakPtr();
36   WeakPtr<WeakClass> weak_ptr_copied(weak_ptr2);
37   WeakPtr<WeakClass> weak_ptr_copied2 = weak_ptr_copied;  // NOLINT
38 
39   ASSERT_TRUE(weak_ptr1);
40   ASSERT_TRUE(weak_ptr2);
41   ASSERT_TRUE(weak_ptr_copied);
42   ASSERT_TRUE(weak_ptr_copied2);
43 
44   ASSERT_EQ(owned_instance.get(), weak_ptr1.get());
45   ASSERT_EQ(owned_instance.get(), weak_ptr2.get());
46   ASSERT_EQ(owned_instance.get(), weak_ptr_copied.get());
47   ASSERT_EQ(owned_instance.get(), weak_ptr_copied2.get());
48 
49   WeakPtr<WeakClass> weak_ptr_moved1(std::move(weak_ptr1));
50   WeakPtr<WeakClass> weak_ptr_moved2(weak_ptr_copied2);
51   weak_ptr_moved2 = std::move(weak_ptr2);
52   ASSERT_FALSE(weak_ptr1);
53   ASSERT_FALSE(weak_ptr2);
54   ASSERT_TRUE(weak_ptr_moved1);
55   ASSERT_TRUE(weak_ptr_moved2);
56   ASSERT_TRUE(weak_ptr_copied2);
57   ASSERT_EQ(owned_instance.get(), weak_ptr_moved1.get());
58   ASSERT_EQ(owned_instance.get(), weak_ptr_moved2.get());
59 
60   owned_instance.reset();
61 
62   ASSERT_FALSE(weak_ptr1);
63   ASSERT_FALSE(weak_ptr2);
64   ASSERT_FALSE(weak_ptr_copied);
65   ASSERT_FALSE(weak_ptr_copied2);
66   ASSERT_FALSE(weak_ptr_moved1);
67   ASSERT_FALSE(weak_ptr_moved2);
68 }
69 
70 }  // namespace
71 }  // namespace base
72 }  // namespace perfetto
73