C ++ 11 /生成的构造函数 [英] C++11 / Generated constructor
问题描述
我一直在从事其他人(离开公司)启动的C ++项目。他写了一段看起来不错的代码,但我听不懂。
I have been working on a C++ project started by someone else (who left the company). He has written a piece of code which seems to work pretty well but I cannot understand it.
下面是该代码的简化版:
Here is below a simplified version of the code:
有两个类别:
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();
}
};
主要:
有在主函数中进行以下调用:
There is the following call in the main function:
char * pMyFileName = agrv[1] ;
Algo_t MyAlgo(ifstream(pMyFileName));
首先,我很惊讶该代码编译时没有任何错误,因为没有 Algo_t
以 ifstream
作为参数。
我更惊讶地注意到这段代码很好用。
First I was very surprised that the code compiled without any error because there is no constructor of Algo_t
taking ifstream
as a parameter.
I was more surprised to notice that this code works very well.
是编译器生成的构造函数还是C ++引入了一些新功能11(带有右值...)?
Are the constructor generated by the compiler or there is some new feature introduced by C++11 (with the rvalue...)?
推荐答案
在C ++中,最多允许一个用户定义的转换。您不能直接从 ifstream
构造 Algo_t
,但是可以构造 Matrix_t
和 ifstream
。因此,在
In C++ you are allowed up to one user defined conversion. You cannot directly construct a Algo_t
from a ifstream
but you can construct a Matrix_t
with a ifstream
. So in
Algo_t MyAlgo(ifstream(pMyFileName));
编译器构造一个临时 Matrix_t
(您的一个用户定义的转化),然后您使用该临时变量来构造 MyAlgo
The compiler construct a temporary Matrix_t
(your one user defined conversion) and then you use that temporary to construct MyAlgo
这篇关于C ++ 11 /生成的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!