Reputation: 9240
I am implementing a smartpointer-template and there is one thing that boogles me; how do I increase the reference counter when passing a smartpointer as a parameter to another function? What operator do I overload to increase ref count?
For example:
class test
{
test() { }
~test() { }
};
void A()
{
SmartPointer<test> p;
B(p);
}
void B(SmartPointer<test> p)
{
C(p);
}
void C(SmartPointer<test> p)
{
// p ref count is still 1 and will be destroyed at end of C
}
Thanks
Upvotes: 0
Views: 744
Reputation: 617
When you pass a parameter it is copied, which will call the copy constructor. It is generally a good idea to overload the equality operator at the same time.
Either that or use boost::shared_ptr or some other per-existing class. Is ther some reason you are not using this?
Upvotes: 2
Reputation: 103703
It should be taken care of in your copy constructor, and also your assignment operator.
Upvotes: 1
Reputation: 477040
All constructors of your smart pointer must manipulate the refcount, including the copy constructor, and the assignment operator must also be involved.
If this puzzles you, it might be too early for you to write your own smart pointers; instead, you could use the high-quality std::shared_ptr
for the time being.
Upvotes: 5