我一直在处理一个由其他人(已经离开公司)开始的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 引入了一些新特性(如右值引用)?
Matrix_t
有一个ifstream
转换运算符,或者一个接受ifstream
的构造函数?哦,该死,它确实有...这就解释了一切... - barak manosconst char []
的std::string
构造结构相同,例如std::stringstream("Hello World!")
- 您不需要显式执行std::stringstream(std::string("Hello World!"))
。 - Holt