2
# tag: cpp, werror, cpp14, no-cpp-locals
4
from libcpp.memory cimport unique_ptr, shared_ptr, default_delete, dynamic_pointer_cast, make_unique
5
from libcpp cimport nullptr
7
cdef extern from "cpp_smart_ptr_helper.h":
8
cdef cppclass CountAllocDealloc:
9
CountAllocDealloc(int*, int*)
11
cdef cppclass FreePtr[T]:
14
cdef cppclass RaiseOnConstruct:
18
ctypedef const CountAllocDealloc const_CountAllocDealloc
25
cdef int alloc_count = 0, dealloc_count = 0
26
cdef unique_ptr[CountAllocDealloc] x_ptr
27
x_ptr.reset(new CountAllocDealloc(&alloc_count, &dealloc_count))
28
assert alloc_count == 1
30
assert alloc_count == 1
31
assert dealloc_count == 1
33
##Repeat the above test with an explicit default_delete type
36
cdef unique_ptr[CountAllocDealloc,default_delete[CountAllocDealloc]] x_ptr2
37
x_ptr2.reset(new CountAllocDealloc(&alloc_count, &dealloc_count))
38
assert alloc_count == 1
40
assert alloc_count == 1
41
assert dealloc_count == 1
45
cdef unique_ptr[CountAllocDealloc,FreePtr[CountAllocDealloc]] x_ptr3
46
x_ptr3.reset(new CountAllocDealloc(&alloc_count, &dealloc_count))
47
assert x_ptr3.get() != nullptr;
49
assert x_ptr3.get() == nullptr;
51
# Test that make_unique works
52
cdef unique_ptr[int] x_ptr4
53
x_ptr4 = make_unique[int](5)
54
assert(x_ptr4) != nullptr
55
cdef unique_ptr[RaiseOnConstruct] x_ptr5
57
x_ptr5 = make_unique[RaiseOnConstruct]()
59
pass # good - this is what we expect
62
def test_const_shared_ptr():
64
>>> test_const_shared_ptr()
66
cdef int alloc_count = 0, dealloc_count = 0
67
cdef shared_ptr[const CountAllocDealloc] ptr = shared_ptr[const_CountAllocDealloc](
68
new CountAllocDealloc(&alloc_count, &dealloc_count))
69
assert alloc_count == 1
70
assert dealloc_count == 0
72
cdef shared_ptr[const CountAllocDealloc] ptr2 = ptr
73
assert alloc_count == 1
74
assert dealloc_count == 0
77
assert alloc_count == 1
78
assert dealloc_count == 0
81
assert alloc_count == 1
82
assert dealloc_count == 1
86
void some_method(): # Force this to be a polymorphic class for dynamic cast.
95
cdef shared_ptr[A] holding_subclass = shared_ptr[A](new C())
98
def test_assignment_to_base_class():
100
>>> test_assignment_to_base_class()
102
cdef shared_ptr[C] derived = shared_ptr[C](new C())
103
cdef shared_ptr[A] base = derived
106
def test_dynamic_pointer_cast():
108
>>> test_dynamic_pointer_cast()
110
cdef shared_ptr[B] b = shared_ptr[B](new B())
111
cdef shared_ptr[A] a = dynamic_pointer_cast[A, B](b)
112
assert a.get() == b.get()
114
a = shared_ptr[A](new A())
115
b = dynamic_pointer_cast[B, A](a)
116
assert b.get() == NULL