将智能指针作为参数传递给函数

Kai*_*aan 0 c++ memory-management smart-pointers reference-counting

我正在实施一个smartpointer模板,有一件事让我感到困惑; 将smartpointer作为参数传递给另一个函数时,如何增加引用计数器?我重载什么操作符来增加引用计数?

例如:

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
}
Run Code Online (Sandbox Code Playgroud)

谢谢

Ker*_* SB 5

智能指针的所有构造函数都必须操作引用计数,包括复制构造函数,并且还必须包含赋值运算符.

如果这让你感到困惑,那么编写自己的智能指针可能为时尚早; 相反,你可以std::shared_ptr暂时使用高品质.