language: C++11 (gcc-4.7.2)
date: 541 days 9 hours ago
link:
visibility: public
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include <memory>
#include <cstdio>
#include <string>
 
namespace clone_ptr_detail
{
template <class T>
class clone_ptr_helper_base
{
public:
    virtual ~clone_ptr_helper_base() {}
    virtual T* clone(const T* source) const = 0;
    virtual void destroy(const T* p) const = 0;
};
 
template <class T, class U>
class clone_ptr_helper: public clone_ptr_helper_base<T>
{
public:
    virtual T* clone(const T* source) const
    {
        return new U(static_cast<const U&>(*source));
    }
    virtual void destroy(const T* p) const
    {
        delete static_cast<const U*>(p);
    }
};
}
 
template <class T>
class clone_ptr
{
    T* ptr;
    std::shared_ptr<clone_ptr_detail::clone_ptr_helper_base<T>> ptr_helper;
public:
    template <class U>
    explicit clone_ptr(U* p): ptr(p), ptr_helper(new clone_ptr_detail::clone_ptr_helper<T, U>()) {}
 
    clone_ptr(const clone_ptr& other): ptr(other.ptr_helper->clone(other.ptr)), ptr_helper(other.ptr_helper) {}
 
    clone_ptr& operator=(clone_ptr rhv)
    {
        swap(rhv);
        return *this;
    }
    ~clone_ptr()
    {
        ptr_helper->destroy(ptr);
    }
 
    T* get() const { /*error checking here*/ return ptr; }
    T& operator* () const { return *get(); }
    T* operator-> () const { return get(); }
 
    void swap(clone_ptr& other)
    {
        std::swap(ptr, other.ptr);
        ptr_helper.swap(other.ptr_helper);
    }
};
 
struct A
{
    virtual void foo() { puts("A::foo"); }
};
 
struct B: A
{
    std::string id;
    B(const std::string& id): id(id) {}
    B(const B& other): id("Copy of " + other.id) {}
    ~B() { puts("~B"); }
    virtual void foo() { puts(id.c_str()); }
};
 
int main()
{
    clone_ptr<A> a(new B("B_instance"));
    clone_ptr<A> b(a);
    a->foo();
    (*b).foo();
    clone_ptr<A> c(new A);
    a = c;
    a->foo();
}