Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer container class which can't be copied by value

Tags:

c++

templates

I need a smart pointer for my project which can be send to several methods as parameter. I have checked auto_ptr and shared_ptr from boost. But IMO, that is not suitable for my requirements. Following are my findings

auto_ptr : When passed to another method, ownership will be transferred and underlying pointer will get deleted when that method's scope ends. We can workaround this by passing auto_ptr by reference, but there is no compile time mechanism to ensure it is always passed by reference. If by mistake, user forgot to pass a reference, it will make problems.

boost::shared_ptr : This looks promising and works correctly for my need. But I feel this is overkill for my project as it is a very small one.

So I decided to write a trivial templated pointer container class which can't be copied by value and take care about deleting the underlying pointer. Here it is

template <typename T>
class simple_ptr{
public:
    simple_ptr(T* t){
       pointer = t;
    }
    ~simple_ptr(){
       delete pointer;
    }
    T* operator->(){
       return pointer;
    }
private: 
    T* pointer;
    simple_ptr(const simple_ptr<T>& t);
};

Is this implementation correct? I have made copy constructor as private, so that compiler will alert when someone tries to pass it by value.

If by chance the pointer is deleted, delete operation on the destructor will throw assertion error. How can I workaround this?

I am pretty new to C++ and your suggestion are much appreciated.

Thanks

like image 522
Navaneeth K N Avatar asked Jul 21 '26 05:07

Navaneeth K N


1 Answers

Please use boost::scoped_ptr<> as suggested by Martin York, because it:

  • Does exactly what you want (it's a noncopyable pointer)
  • Has no overhead above that of a standard C pointer
  • Has been carefully crafted by super-intelligent C++ wizards to make sure it behaves as expected.

While I can't see any problems with your implementation (after applying the changes suggested by ChrisW), C++ has many dark corners and I would not be surprised if there is some obscure corner case which you, I and the others here have failed to spot.

like image 98
j_random_hacker Avatar answered Jul 23 '26 20:07

j_random_hacker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!