特定のオブジェクトが参照されるプロジェクトに取り組んでいます。これは、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;
}