Kev*_*vin 7 c++ overloading smart-pointers operator-overloading
我正在研究一个项目,其中某些对象被引用计数 - 它与COM的设置非常相似.无论如何,我们的项目确实有智能指针,可以减少为这些对象显式调用Add()和Release()的需要.问题是,有时开发人员仍然使用智能指针调用Release().
我正在寻找的方法是从智能指针调用Release()创建编译时或运行时错误.编译时似乎不可能.我以为我有一个运行时解决方案(见下面的代码),但它也没有完全编译.显然,使用operator - >()后不允许隐式转换.
无论如何,任何人都可以想到一种方法来完成我想要完成的任务吗?
非常感谢您的帮助!
凯文
#include <iostream>
#include <cassert>
using namespace std;
class A
{
public:
void Add()
{
cout << "A::Add" << endl;
}
void Release()
{
cout << "A::Release" << endl;
}
void Foo()
{
cout << "A::Foo" << endl;
}
};
template <class T>
class MySmartPtrHelper
{
T* m_t;
public:
MySmartPtrHelper(T* _t)
: m_t(_t)
{
m_t->Add();
}
~MySmartPtrHelper()
{
m_t->Release();
}
operator T&()
{
return *m_t;
}
void Add()
{
cout << "MySmartPtrHelper::Add()" << endl;
assert(false);
}
void Release()
{
cout << "MySmartPtrHelper::Release()" << endl;
assert(false);
}
};
template <class T>
class MySmartPtr
{
MySmartPtrHelper<T> m_helper;
public:
MySmartPtr(T* _pT)
: m_helper(_pT)
{
}
MySmartPtrHelper<T>* operator->()
{
return &m_helper;
}
};
int main()
{
A a;
MySmartPtr<A> pA(&a);
pA->Foo(); // this currently fails to compile. The compiler
// complains that MySmartPtrHelper::Foo() doesn't exist.
//pA->Release(); // this will correctly assert if uncommented.
return 0;
}
Run Code Online (Sandbox Code Playgroud)
你不能这样做——一旦你重载了,operator ->你就被卡住了——重载的运算符将以同样的方式表现,不管它的右边是什么。
您可以将 Add() 和 Release() 方法声明为私有,并使智能指针成为引用计数类的友元。