]>
Commit | Line | Data |
---|---|---|
7c673cae FG |
1 | /*============================================================================= |
2 | Copyright (c) 2007 Tobias Schwinger | |
3 | ||
4 | Use modification and distribution are subject to the Boost Software | |
5 | License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at | |
6 | http://www.boost.org/LICENSE_1_0.txt). | |
7 | ==============================================================================*/ | |
8 | ||
9 | #include <boost/functional/factory.hpp> | |
10 | #include <boost/detail/lightweight_test.hpp> | |
11 | ||
12 | #include <cstddef> | |
13 | #include <memory> | |
14 | #include <boost/shared_ptr.hpp> | |
15 | ||
16 | using std::size_t; | |
17 | ||
18 | class sum | |
19 | { | |
20 | int val_sum; | |
21 | public: | |
22 | sum(int a, int b) : val_sum(a + b) { } | |
23 | ||
24 | operator int() const { return this->val_sum; } | |
25 | }; | |
26 | ||
27 | template< typename T > | |
28 | class counting_allocator : public std::allocator<T> | |
29 | { | |
30 | public: | |
31 | counting_allocator() | |
32 | { } | |
33 | ||
34 | template< typename OtherT > | |
35 | struct rebind { typedef counting_allocator<OtherT> other; }; | |
36 | ||
37 | template< typename OtherT > | |
38 | counting_allocator(counting_allocator<OtherT> const& that) | |
39 | { } | |
40 | ||
41 | static size_t n_allocated; | |
42 | T* allocate(size_t n, void const* hint = 0l) | |
43 | { | |
44 | n_allocated += 1; | |
45 | return std::allocator<T>::allocate(n,hint); | |
46 | } | |
47 | ||
48 | static size_t n_deallocated; | |
49 | void deallocate(T* ptr, size_t n) | |
50 | { | |
51 | n_deallocated += 1; | |
52 | return std::allocator<T>::deallocate(ptr,n); | |
53 | } | |
54 | }; | |
55 | template< typename T > size_t counting_allocator<T>::n_allocated = 0; | |
56 | template< typename T > size_t counting_allocator<T>::n_deallocated = 0; | |
57 | ||
58 | int main() | |
59 | { | |
60 | int one = 1, two = 2; | |
61 | { | |
62 | boost::shared_ptr<sum> instance( | |
63 | boost::factory< boost::shared_ptr<sum>, counting_allocator<void>, | |
64 | boost::factory_alloc_for_pointee_and_deleter >()(one,two) ); | |
65 | BOOST_TEST(*instance == 3); | |
66 | } | |
67 | BOOST_TEST(counting_allocator<sum>::n_allocated == 1); | |
68 | BOOST_TEST(counting_allocator<sum>::n_deallocated == 1); | |
69 | { | |
70 | boost::shared_ptr<sum> instance( | |
71 | boost::factory< boost::shared_ptr<sum>, counting_allocator<void>, | |
72 | boost::factory_passes_alloc_to_smart_pointer >()(one,two) ); | |
73 | BOOST_TEST(*instance == 3); | |
74 | } | |
75 | BOOST_TEST(counting_allocator<sum>::n_allocated == 2); | |
76 | BOOST_TEST(counting_allocator<sum>::n_deallocated == 2); | |
77 | return boost::report_errors(); | |
78 | } | |
79 |