C ++ 11 / Genrated构造函数 [英] C++11 / Genrated 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 / Genrated构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!