I have the following sample code (a stripped down version of my programme)
Class ‘some_class’ has a constructor with default parameters. The compiler is able to recognise this constructor as a copy constructor. In the main function, this constructor is called when I order for a copy constructed object called ‘b’. But when I construct ‘c’ from a function result, the compiler calls a compiler generated copy constructor (which copies the bit pattern). I can tell by the value of c.some_data, which should have been set by my own copy constructor to a value of 2.
1) What does the standard say about this?
2) Is my compiler broken?
I use MinGW with no options but a specification of my source file name and a name for the executable. I got my port of the gnu open source compiler from the official MinGW website, I’m using the latest version. Have I found a bug, or is this due to my (mis)understanding of c++?
Thanks in advance
#include <iostream>
#include <string>
class some_class
{
public:
some_class(int p = 0) :
some_data(p)
{
std::cout << "user defined constructor (p = " << p << ")" << std::endl;
}
some_class(const some_class &, int = 0)
{
std::cout << "user defined copy constructor" << std::endl;
some_data = 2;
}
int some_data;
};
extern some_class some_function_returning_some_class_object();
int main(int, char **)
{
std::cout << "creating a, with no parameters" << std::endl;
some_class a;
std::cout << "creating b, a copy of a" << std::endl;
some_class b = a;
std::cout << "creating c, copy constructed from a function result" << std::endl;
some_class c = some_function_returning_some_class_object();
std::cout << "c.some_data = " << c.some_data << std::endl;
}
some_class some_function_returning_some_class_object()
{
some_class a(1);
return a;
}
The output is as follows:
creating a, with no parameters
user defined constructor (p = 0)
creating b, a copy of a
user defined copy constructor
creating c, copy constructed from a function result
user defined constructor (p = 1)
c.some_data = 1
The compiler is not using the compiler-defined default copy constructor. It is presumably using return value optimization to skip the copy altogether.