将智能指针作为参数传递给函数
我正在实现一个智能指针模板,有一件事让我感到困惑;将智能指针作为参数传递给另一个函数时如何增加引用计数器?我应该重载什么运算符来增加引用计数?
例如:
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
}
谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
智能指针的所有构造函数都必须操作引用计数,包括复制构造函数,并且还必须涉及赋值运算符。
如果这让您感到困惑,那么您现在编写自己的智能指针可能还为时过早;相反,您可以暂时使用高质量的
std::shared_ptr
。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.当您传递参数时,它会被复制,这将调用复制构造函数。同时重载相等运算符通常是一个好主意。
或者使用 boost::shared_ptr 或其他一些现有的类。您不使用这个有什么原因吗?
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?
应该在复制构造函数和赋值运算符中处理它。
It should be taken care of in your copy constructor, and also your assignment operator.