Copy Constructor May Not Be Generated
The C++ standard says that a copy constructor will be called when an object is moved, such that, an object will be created and destroyed at the same address.
However, when compiling with /clr, and when a function compiled to MSIL calls a native function, passing one or more native classes by value, and where the native class has a copy constructor and/or destructor, no copy constructor will be called and the object will be destroyed at a different address than where it was created.
This could result in problems if the class has a pointer into itself, or if the code is tracking objects by address.
For more information, see /clr (Common Language Runtime Compilation).
Example
Description
The following sample demonstrates when a copy constructor will not be generated.
Code
// breaking_change_no_copy_ctor.cpp
// compile with: /clr
#include<stdio.h>
struct S {
int i;
static int n;
S() : i(n++) {
printf_s("S object %d being constructed, this=%p\n", i, this);
}
S(S const& rhs) : i(n++) {
printf_s("S object %d being copy constructed from S object "
"%d, this=%p\n", i, rhs.i, this);
}
~S() {
printf_s("S object %d being destroyed, this=%p\n", i, this);
}
};
int S::n = 0;
#pragma managed(push,off)
void f(S s1, S s2) {
printf_s("in function f\n");
}
#pragma managed(pop)
int main() {
S s;
S t;
f(s,t);
}
Sample Output
S object 0 being constructed, this=0018F378
S object 1 being constructed, this=0018F37C
S object 2 being copy constructed from S object 1, this=0018F380
S object 3 being copy constructed from S object 0, this=0018F384
S object 4 being copy constructed from S object 2, this=0018F2E4
S object 2 being destroyed, this=0018F380
S object 5 being copy constructed from S object 3, this=0018F2E0
S object 3 being destroyed, this=0018F384
in function f
S object 5 being destroyed, this=0018F2E0
S object 4 being destroyed, this=0018F2E4
S object 1 being destroyed, this=0018F37C
S object 0 being destroyed, this=0018F378