C++/CLI Finalizers and Operators
-
06-07-2019 - |
Question
In the following example, I get:
error C2300: 'UnmanagedClass' : class does not have a finalizer called '!SmartPointer'
If I remove the operator->, this error goes away. Could someone explain why this is happening?
// Unmanaged class.
class UnmanagedClass { };
public ref class SmartPointer {
public:
SmartPointer(UnmanagedClass* u) : m_ptr(u) { }
~SmartPointer() { this->!SmartPointer(); }
!SmartPointer() { delete m_ptr; }
// This line triggers C2300.
UnmanagedClass* operator->() { return m_ptr; }
};
int main() {
SmartPointer^ s = gcnew SmartPointer(new UnmanagedClass);
}
Solution
You're overriding the -> operator, so when you do:
~SmartPointer() { this->!SmartPointer(); }
You're effectively calling
~SmartPointer() { m_ptr->!SmartPointer(); }
I believe you can work around this by doing this, though:
~SmartPointer() { (*this).!SmartPointer(); }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow