I
Ian
I was under the impression that the following produced the same IL code:
A ^a = gcnew A();
A a;
The first line creates object 'a' using gcnew while the second line creates
object 'a' using stack based code. I understood both methods produce the
same object - is this true? If not, what is the difference between the
objects created using gcnew and stack based code?
The lines numbered 6 to 11 below illustrate that the constructor called
depends upon the method used to create an object. Lines 5, 8 and 10 call
constructor #4 while lines 7, 9 and 11 call constructor #3. Given that
all objects are supposedly allocated on the managed heap, I expected only
constructor #4 would be called. Would someone kindly explain what is
happening here? Why does a 'pseudo' stack based object produce different
results than objects created using gcnew?
Thanks
Ian
ref class A
{
public:
A() { // ctor #1
iValue = 0;
};
A( const int i ) { // ctor #2
iValue = i;
}
A( const A% a ) { // ctor #3
iValue = a.iValue;
}
A( const A^ a ) { // ctor #4
iValue = a->iValue;
}
int iValue;
};
A ^a1 = gcnew A( 1 ); // (1) calls ctor #2
A a2 = gcnew A( 2 ); // (2) calls ctor #2
A a3( 2 ); // (3) calls ctor #2
A ^b1 = a1; // (4) ctor not called
A b2 = a1; // (5) calls ctor #4
//A ^b3 = a2; // (6) compiler error 2440
A b4 = a2; // (7) calls ctor #3
A ^c1 = gcnew A( a1 ); // (8) calls ctor #4
A ^c2 = gcnew A( a2 ); // (9) calls ctor #3
A c3 = gcnew A( a1 ); // (10) calls ctor #4
A c4 = gcnew A( a2 ); // (11) calls ctor #3
A ^a = gcnew A();
A a;
The first line creates object 'a' using gcnew while the second line creates
object 'a' using stack based code. I understood both methods produce the
same object - is this true? If not, what is the difference between the
objects created using gcnew and stack based code?
The lines numbered 6 to 11 below illustrate that the constructor called
depends upon the method used to create an object. Lines 5, 8 and 10 call
constructor #4 while lines 7, 9 and 11 call constructor #3. Given that
all objects are supposedly allocated on the managed heap, I expected only
constructor #4 would be called. Would someone kindly explain what is
happening here? Why does a 'pseudo' stack based object produce different
results than objects created using gcnew?
Thanks
Ian
ref class A
{
public:
A() { // ctor #1
iValue = 0;
};
A( const int i ) { // ctor #2
iValue = i;
}
A( const A% a ) { // ctor #3
iValue = a.iValue;
}
A( const A^ a ) { // ctor #4
iValue = a->iValue;
}
int iValue;
};
A ^a1 = gcnew A( 1 ); // (1) calls ctor #2
A a2 = gcnew A( 2 ); // (2) calls ctor #2
A a3( 2 ); // (3) calls ctor #2
A ^b1 = a1; // (4) ctor not called
A b2 = a1; // (5) calls ctor #4
//A ^b3 = a2; // (6) compiler error 2440
A b4 = a2; // (7) calls ctor #3
A ^c1 = gcnew A( a1 ); // (8) calls ctor #4
A ^c2 = gcnew A( a2 ); // (9) calls ctor #3
A c3 = gcnew A( a1 ); // (10) calls ctor #4
A c4 = gcnew A( a2 ); // (11) calls ctor #3