1 /*
2 Copyright 2007 Tobias Schwinger
3
4 Copyright 2019 Glen Joseph Fernandes
5 (glenjofe@gmail.com)
6
7 Distributed under the Boost Software License, Version 1.0.
8 (http://www.boost.org/LICENSE_1_0.txt)
9 */
10 #include <boost/functional/factory.hpp>
11 #include <boost/core/lightweight_test.hpp>
12 #include <boost/smart_ptr/shared_ptr.hpp>
13
14 class sum {
15 public:
sum(int a,int b)16 sum(int a, int b)
17 : value_(a + b) { }
18
get() const19 int get() const {
20 return value_;
21 }
22
23 private:
24 int value_;
25 };
26
27 template<class T>
28 class creator {
29 public:
30 static int count;
31
32 typedef T value_type;
33 typedef T* pointer;
34
35 template<class U>
36 struct rebind {
37 typedef creator<U> other;
38 };
39
creator()40 creator() { }
41
42 template<class U>
creator(const creator<U> &)43 creator(const creator<U>&) { }
44
allocate(std::size_t size)45 T* allocate(std::size_t size) {
46 ++count;
47 return static_cast<T*>(::operator new(sizeof(T) * size));
48 }
49
deallocate(T * ptr,std::size_t)50 void deallocate(T* ptr, std::size_t) {
51 --count;
52 ::operator delete(ptr);
53 }
54 };
55
56 template<class T>
57 int creator<T>::count = 0;
58
59 template<class T, class U>
60 inline bool
operator ==(const creator<T> &,const creator<U> &)61 operator==(const creator<T>&, const creator<U>&)
62 {
63 return true;
64 }
65
66 template<class T, class U>
67 inline bool
operator !=(const creator<T> &,const creator<U> &)68 operator!=(const creator<T>&, const creator<U>&)
69 {
70 return false;
71 }
72
main()73 int main()
74 {
75 int a = 1;
76 int b = 2;
77 {
78 boost::shared_ptr<sum> s(boost::factory<boost::shared_ptr<sum>,
79 creator<void>,
80 boost::factory_alloc_for_pointee_and_deleter>()(a, b));
81 BOOST_TEST(creator<sum>::count == 1);
82 BOOST_TEST(s->get() == 3);
83 }
84 BOOST_TEST(creator<sum>::count == 0);
85 {
86 boost::shared_ptr<sum> s(boost::factory<boost::shared_ptr<sum>,
87 creator<void>,
88 boost::factory_passes_alloc_to_smart_pointer>()(a, b));
89 BOOST_TEST(creator<sum>::count == 1);
90 BOOST_TEST(s->get() == 3);
91 }
92 BOOST_TEST(creator<sum>::count == 0);
93 return boost::report_errors();
94 }
95
96