'New' in initialization list.

R

rwf_20

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
 
C

Carl Daniel [VC++ MVP]

rwf_20 said:
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?

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
 
B

Ben Voigt [C++ MVP]

rwf_20 said:
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?

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).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top