Smart Pointers with templates

Discussion in 'C++' started by Shiva, Dec 1, 2004.

  1. Shiva

    Shiva Guest

    I saw C++ FAQ LITE on how to go about creating a smart pointer.

    I tried my hand at creating a smart pointer using templates. I'm
    thinking of creating just one Pointer class to create pointers for all
    classes. Here's a code excerpt.

    class Object {
    //This is a bare bones definition for Object
    //Not complete yet.
    int _objIdentifier;
    public:
    Object() {
    }
    };

    template<typename T>
    class Pointer;

    class MyClass : public virtual Object {
    private:
    friend Pointer<MyClass>;
    MyClass() {
    x = 0;
    std::cout << "MyClass::Constructor" << endl;
    }
    public:
    int x;
    ~MyClass() {
    std::cout << "MyClass::Destructor" << endl;
    }
    };

    template<typename T>
    class Pointer : public virtual Object {
    private:
    T *_data;
    public:
    Pointer() {
    _data = new T;
    }
    ~Pointer() {
    delete _data;
    }
    T *operator->(void) {
    return _data;
    }
    };

    I think this works with the restriction that I will have to always use
    the default constructor and that every class in my application should
    create one and only private default constructor.

    Am I missing something? What potential problems will I have if I
    institutionalize this in our Architecture?
     
    Shiva, Dec 1, 2004
    #1
    1. Advertising


  2. >I saw C++ FAQ LITE on how to go about creating a smart pointer.
    >
    > I tried my hand at creating a smart pointer using templates. I'm
    > thinking of creating just one Pointer class to create pointers for all
    > classes. Here's a code excerpt.
    >> Am I missing something? What potential problems will I have if I

    > institutionalize this in our Architecture?


    You might look into the boost shared_ptr template. See
    C:\boost_1_31_0\libs\smart_ptr\smart_ptr.htm
     
    Kurt Krueckeberg, Dec 1, 2004
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. JKop
    Replies:
    3
    Views:
    477
  2. MotoK
    Replies:
    59
    Views:
    1,818
    Keith Thompson
    Sep 15, 2006
  3. n2xssvv g02gfr12930

    Smart pointers and member function pointers

    n2xssvv g02gfr12930, Nov 26, 2005, in forum: C++
    Replies:
    3
    Views:
    472
    n2xssvv g02gfr12930
    Nov 27, 2005
  4. recover
    Replies:
    2
    Views:
    809
    recover
    Jul 25, 2006
  5. cerr

    pointers, pointers, pointers...

    cerr, Apr 7, 2011, in forum: C Programming
    Replies:
    12
    Views:
    681
Loading...

Share This Page