C 编译器可以在用户定义和编译器生成的复制构建器之间进行自由选择

c++ compiler free to choose between user defined and compiler generated copy-constructors?

本文关键字:编译器 构建 复制 之间 自由选择 用户 定义      更新时间:2023-10-16

我有以下示例代码(我的程序的删除版本)

类'Some_class'具有带有默认参数的构造函数。编译器能够识别该构造函数是复制构造函数。在主函数中,当我订购一个称为" 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

编译器未使用编译器定义的默认复制构造函数。大概是使用返回值优化来完全跳过副本。