Using std::shared_ptr to point to anything

后端 未结 4 1957
醉梦人生
醉梦人生 2020-12-16 23:42

I\'m using a std::shared_ptr in my application to make a smart pointer which can point to many different types of data structures like structs, vect

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-17 00:20

    You can.

    #include 
    #include 
    #include 
    
    using namespace std;
    
    class wild_ptr {
        shared_ptr v;
    public:
        template 
        void set(T v) {
            this->v = make_shared(v);
        }
    
        template 
        T & ref() {
            return (*(T*)v.get());
        }
    };
    
    int main(int argc, char* argv[])
    {
        shared_ptr a;
        a = make_shared(3);
        cout << (*(int*)a.get()) << '\n';
        cout << *static_pointer_cast(a) << '\n'; // same as above
    
        wild_ptr b;
        cout << sizeof(b) << '\n';
        b.set(3);
        cout << b.ref() << '\n';
        b.ref() = 4;
        cout << b.ref() << '\n';
    
        b.set("foo");
        cout << b.ref() << '\n';
    
        b.set(string("bar"));
        cout << b.ref() << '\n';
        return 0;
    }
    

    Output:

    3
    3
    8
    3
    4
    foo
    bar
    

提交回复
热议问题