C ++ 11 / Generated Constructor

I am working on a C ++ project launched by someone else (who left the company). He wrote a piece of code that seems to work very well, but I can't figure it out.

The following is 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();
    }
};

Primarily:

The main function has the following call:

char * pMyFileName = agrv[1] ;
Algo_t MyAlgo(ifstream(pMyFileName));
At first I was very surprised that the code compiled without errors, because there is no constructor Algo_tthat takes ifstreamas a parameter. I was more surprised to notice that this code works very well.

Is the constructor generated by the compiler, or is there some new function introduced by C ++ 11 (with rvalue ...)?

+4
source share
3 answers

++ . Algo_t ifstream, Matrix_t ifstream. ,

Algo_t MyAlgo(ifstream(pMyFileName));

Matrix_t ( ), MyAlgo

+8

:

: .

, ifstream Matrix_t - :

Matrix_t(std::ifstream && ifstream)

, :

Algo_t MyAlgo(ifstream(pMyFileName));

ifstream(pMyFileName) Matrix_t, Algo_t(Matrix_t && Matrix)

+4

Your matrix constructor is implicitly called since it accepts ifstream&&. If you make it explicit, this will not work:

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

Source: https://habr.com/ru/post/1649792/


All Articles