我有以下示例代码(我的程序的精简版)
类'some_class'有一个带默认参数的构造函数。编译器能够将此构造函数识别为复制构造函数。在main函数中,当我订购一个名为'b'的复制构造对象时,会调用此构造函数。但是当我从函数结果构造'c'时,编译器调用编译器生成的复制构造函数(复制位模式)。我可以通过c.some_data的值来判断,它应该由我自己的复制构造函数设置为值2.
1)标准对此有何评价? 2)我的编译器坏了吗?
我使用MinGW没有选项,只有源文件名的规范和可执行文件的名称。我从官方的MinGW网站上获得了我的gnu开源编译器的端口,我正在使用最新版本。我是否发现了一个错误,或者这是由于我对c ++的错误理解?
提前致谢
#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;
}
输出如下:
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