c++ 编译器可以在用户定义的和编译器生成的复制构造函数之间自由选择?

问题描述 投票:0回答:1

我有以下示例代码(我程序的精简版)

Class '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
c++ mingw gnu copy-constructor
1个回答
4
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.