Copying objects

  • Thread starter Thread starter kevin_g_frey
  • Start date Start date
K

kevin_g_frey

Hello All,

I do in fact feel rather stupid asking this question, but I will ask
nonetheless:

What is the correct way for performing a memberwise copy of an object
under Managed C++?

To use a very simple example:

DateTimeFormatInfo* format_info = new DateTimeFormatInfo;
// want to copy the invariant info - this doesn't compile
*format_info = *DateTimeFormatInfo::InvariantInfo;

I am obviously missing something in my understanding...

The closest I have come to achieving this (which is not a memberwise
copy, anyway), is to use the Clone( ) method. Because MC++ does not
seem to support CoVariant return types, however, I have to do this:

DateTimeFormatInfo* format_info = static_cast< DateTimeFormatInfo* >(
DateTimeFormatInfo::InvariantInfo )

which simply looks atrocious for such a simple operation.

Thanks

Kevin
 
a few possibilities come to mind. First,

*format_info = *DateTimeFormatInfo::InvariantInfo;

and

DateTimeFormatInfo* format_info = static_cast< DateTimeFormatInfo* >(
DateTimeFormatInfo::InvariantInfo )

are completely different. Your first statment is an attempt to COPY the
CONTENTS. The second results in two pointers both pointing to the same info
(only one copy exists between the two pointers).

I don't know anything about DateTimeFormatInfo::InvariantInfo, but it
appears from your code it's a pointer to an info structure. If it's actually
an INSTANCE of the info structure then this should work instead:

*format_info = DateTimeFormatInfo::InvariantInfo; // assuming it is a
'simple' stucture, see below

If it IS a pointer, then you might look for any copy constructors or
assignment (=) operator overloads. And, if the info structure isn't
'simple', such as having pointers in it to other structures or variable
length arrays, then it requires some mechanism to copy such things
intelligently.

My 2 cents...
 
Sorry, perhaps I was not clear enough:

DateTimeFormatInfo is a .NET managed class. As such it behaves
according to the rules for managed classes.

DateTimeFormatInfo::InvariantInfo is a static property and returns an
object pointer (of type DateTimeFormatInfo).

My example was based on an attempt to perform a memberwise copy based
on Standard C++ syntax, which obviously does not want to work in
relation to managed objects.
 
Back
Top