Debian Codegraph @

libstdc++-v3/testsuite/20_util/shared_ptr/cons/alias-rval.cc

raw
1 // { dg-do run { target c++20 } }
2 // { dg-require-effective-target hosted }
3
4 // Copyright (C) 2019-2025 Free Software Foundation, Inc.
5 //
6 // This file is part of the GNU ISO C++ Library. This library is free
7 // software; you can redistribute it and/or modify it under the
8 // terms of the GNU General Public License as published by the
9 // Free Software Foundation; either version 3, or (at your option)
10 // any later version.
11
12 // This library is distributed in the hope that it will be useful,
13 // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 // GNU General Public License for more details.
16
17 // You should have received a copy of the GNU General Public License along
18 // with this library; see the file COPYING3. If not see
19 // <http://www.gnu.org/licenses/>.
20
21 // Template class shared_ptr [util.smartptr.shared]
22
23 #include <memory>
24 #include <testsuite_hooks.h>
25
26 struct A
27 {
28 A() : i() { }
29 virtual ~A() { }
30 int i;
31 };
32
33 struct B : A
34 {
35 B() : A(), a() { }
36 virtual ~B() { }
37 A a;
38 };
39
40 // 20.6.6.2.1 shared_ptr constructors [util.smartptr.shared.const]
41
42 // Aliasing constructors
43
44 void
45 test01()
46 {
47 bool test = true;
48
49 std::shared_ptr<A> a;
50 std::shared_ptr<bool> b1(std::move(a), &test);
51 VERIFY( b1.use_count() == 0 );
52 VERIFY( b1.get() == &test );
53 VERIFY( a.use_count() == 0 );
54 VERIFY( a == nullptr );
55
56 std::shared_ptr<bool> b2(b1);
57 VERIFY( b2.use_count() == 0 );
58 VERIFY( b1 == b2 );
59 }
60
61 void
62 test02()
63 {
64 A* ptr = new A;
65 ptr->i = 100;
66 std::shared_ptr<A> a(ptr);
67 std::shared_ptr<int> i1(std::move(a), &a->i);
68 VERIFY( i1.use_count() == 1 );
69 VERIFY( *i1 == 100 );
70 VERIFY( a.use_count() == 0 );
71 VERIFY( a == nullptr );
72
73 std::shared_ptr<int> i2(i1);
74 VERIFY( i2.use_count() == 2 );
75 VERIFY( i2.get() == &ptr->i );
76 }
77
78 void
79 test03()
80 {
81 std::shared_ptr<B> b1(new B);
82 b1->i = 100;
83 b1->a.i = 200;
84 std::shared_ptr<B> b2(b1);
85 std::shared_ptr<A> a1(std::move(b1), b1.get());
86 std::shared_ptr<A> a2(std::move(b2), &b2->a);
87 VERIFY( a1.use_count() == 2 );
88 VERIFY( a2.use_count() == 2 );
89 VERIFY( a1->i == 100 );
90 VERIFY( a2->i == 200 );
91 VERIFY( b1.use_count() == 0 );
92 VERIFY( b2.use_count() == 0 );
93 VERIFY( b1 == nullptr );
94 VERIFY( b2 == nullptr );
95 }
96
97 int
98 main()
99 {
100 test01();
101 test02();
102 test03();
103 }