In standard C++, it is recommended to avoid unmanaged resource
acquisition in initialization lists, such as:
class C {
public:
C(const int i) : m_i(new int(i)) { }
private:
int m_i;
};
I'm assuming this holds for code built via /clr as well. But, do the
'Smart' features of .NET ref types ('^') make this acceptable with
managed types? E.g.
ref class C {
public:
C() : m_obj(gcnew ManagedObject) { }
private:
ManagedObject^ m_obj;
};
Is this safe in VC 8?
Ryan
Carl Daniel [VC++ MVP] - 26 Apr 2008 04:10 GMT
> In standard C++, it is recommended to avoid unmanaged resource
> acquisition in initialization lists, such as:
[quoted text clipped - 18 lines]
>
> Is this safe in VC 8?
Perfectly safe. GC will (eventually) recover the object if the constructor
throws an exception, which is the concern with using new in a
ctor-initializer in native code.
-cd
Ben Voigt [C++ MVP] - 26 Apr 2008 22:03 GMT
> In standard C++, it is recommended to avoid unmanaged resource
> acquisition in initialization lists, such as:
[quoted text clipped - 18 lines]
>
> Is this safe in VC 8?
Will m_obj be reassigned to point to a different object? If not, then use
the stack semantics notation so that Dispose is called on m_obj if the
constructor throws. If it *can* be reassigned and is IDisposable, then does
this class acquire ownership of any other object ever held in m_obj? You
may still want to use RAII to guarantee Dispose is called appropriately (in
C++, you use the delete keyword to call IDisposable::Dispose).
> Ryan