how to design a smart pointer class

smart pointer class is the one that take in charge of release allocated resource when itself destroyed.

recently,i want design a smart pointer class, it take in charge of release resource allocated by new or new[].

my problem how to design destructor, you should determine the pointer ptr is pointer an array or a single object.


the structure of this smart point class may be:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
template<class T>;
class smart_pointer{
public:
  smart_pointer(T* p):ptr(p){};
  ~smart_pointer(){
   //how to determine to use delete[] ptr or delete ptr;
  }
//
  some operator overload functions correspond to pointer
  like [], *, &, ++, --,etc
//

private:
  T* ptr;
}



does anybody has good idea?
you should determine the pointer ptr is pointer an array or a single object.
Impossible. I suggest to use std::unique_ptr approach and have specialisation for pointers to arrays:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>

template <typename T>
class foo //Generic pointer
{
public:
    static void hi() {std::cout << "Pointer\n";}
};

template <typename T>
class foo<T[]> //Array pointer specialisation
{
public:
    static void hi() {std::cout << "Array\n";}
};

int main()
{
    //Usage
    foo<int>::hi(); //calling static method of pointer to object
    foo<int[]>::hi(); //calling static method of pointer to array
}

thanks, you helped me.

but i found there are mistakes in building time, when i define class foo<T[]> {}{ before class foo{}.

and one more question: what's the difference between template<class T> and template<typename T>
but i found there are mistakes in building time, when i define class foo<T[]> {}{ before class foo{}.
This is because foo<T[]> is a specialisation of foo. It makes sense that original should be defined before its specialisation.

what's the difference between template<class T> and template<typename T>
No difference. Those keywords are interchangable here.
thanks, you helped me a lot.
mzzz wrote:
determine the pointer ptr is pointer an array or a single object
Take a look at this:

http://www.cplusplus.com/reference/type_traits/
You cannot check if pointer points to array or single value that way.
However it still worth to take a look at this. It really helps with generic programming.
Last edited on
Topic archived. No new replies allowed.