C++11/生成的构造函数

C++11 / Generated constructor

本文关键字:构造函数 C++11      更新时间:2023-10-16

我一直在做一个由其他人(已离开公司)启动的C++项目。他写了一段代码,看起来运行得很好,但我听不懂

下面是代码的简化版本:

有两类:

class Algo_t {
protected :
    Matrix_t m_Matrix ;
public:
    Algo_t(Matrix_t && Matrix) {
        DoSomething();
    }
};
class Matrix_t {
protected :
    std::ifstream & m_iftsream ;
public:
    Matrix_t(std::ifstream && ifstream) {
        DoSomething();
    }
};

总的来说:

主函数中有以下调用:

char * pMyFileName = agrv[1] ;
Algo_t MyAlgo(ifstream(pMyFileName));

首先,我很惊讶代码编译时没有任何错误,因为Algo_t的构造函数没有将ifstream作为参数。我更惊讶地注意到,这个代码运行得非常好。

构造函数是由编译器生成的,还是C++11引入了一些新功能(带有右值…)?

在C++中,最多允许进行一次用户定义的转换。不能直接从ifstream构造Algo_t,但可以使用ifstream构造Matrix_t。所以在中

Algo_t MyAlgo(ifstream(pMyFileName));

编译器构造一个临时Matrix_t(您的一个用户定义的转换),然后您使用该临时来构造MyAlgo

如下所述:

单参数构造函数:允许从初始化对象的特定类型。

因此,由于构造函数的原因,有一个从ifstreamMatrix_t的隐式转换选项:

Matrix_t(std::ifstream && ifstream)

所以当你打电话给时

Algo_t MyAlgo(ifstream(pMyFileName));

CCD_ 11对象转换为CCD_ 12对象,然后由构造函数CCD_

您的矩阵构造函数是隐式调用的,因为它需要ifstream&&。如果你把它说得很清楚,它就不会起作用:

explicit Matrix_t(std::ifstream && ifstream) {
    DoSomething();
}