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:
There are two classes :
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();
}
};
In the main:
There is the following call in the main function:
char * pMyFileName = agrv[1] ;
Algo_t MyAlgo(ifstream(pMyFileName));
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.
Are the constructor generated by the compiler or there is some new feature introduced by C++11 (with the rvalue...)?
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));
The compiler construct a temporary Matrix_t
(your one user defined conversion) and then you use that temporary to construct MyAlgo
As explained here:
Single-argument constructors: allow implicit conversion from a particular type to initialize an object.
Hence, there is an implicit conversion option from ifstream
to Matrix_t
due to the constructor:
Matrix_t(std::ifstream && ifstream)
So when you called:
Algo_t MyAlgo(ifstream(pMyFileName));
the ifstream(pMyFileName)
object convert to Matrix_t
object and then used by the constructor Algo_t(Matrix_t && Matrix)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With