C++11/生成的构造函数
C++11 / Generated constructor
我一直在做一个由其他人(已离开公司)启动的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引入了一些新功能(带有右值…)?
在C++中,最多允许进行一次用户定义的转换。不能直接从ifstream
构造Algo_t
,但可以使用ifstream
构造Matrix_t
。所以在中
Algo_t MyAlgo(ifstream(pMyFileName));
编译器构造一个临时Matrix_t
(您的一个用户定义的转换),然后您使用该临时来构造MyAlgo
如下所述:
单参数构造函数:允许从初始化对象的特定类型。
因此,由于构造函数的原因,有一个从ifstream
到Matrix_t
的隐式转换选项:
Matrix_t(std::ifstream && ifstream)
所以当你打电话给时
Algo_t MyAlgo(ifstream(pMyFileName));
CCD_ 11对象转换为CCD_ 12对象,然后由构造函数CCD_
您的矩阵构造函数是隐式调用的,因为它需要ifstream&&
。如果你把它说得很清楚,它就不会起作用:
explicit Matrix_t(std::ifstream && ifstream) {
DoSomething();
}
相关文章:
- 继承:构造函数,初始化C++11中基类的类C数组成员
- C++11:没有复制构造函数的自定义基于范围的循环
- 如何在C++11中区分填充构造函数和范围构造函数
- 移动构造函数 C++11
- 构造函数中调用没有匹配函数 - C++ 11
- 防止复制构造函数实例化 C++11 类"deleting"
- =删除用户定义的成员功能,除了构造函数,分配运算符C 11
- SFINAE enable_if 使用 pre c++11 启用构造函数
- 为什么编译器在试图初始化具有C 11样式的对象数组时隐含删除构造函数
- 摘要类可以在C 11中具有构造函数和私人成员
- C 11:可以默认默认构造函数导致部分初始化类
- C 11和类构造函数中的variadic模板
- C 11多移动构造函数调用
- 具有类成员默认值的 C++11 默认构造函数行为
- 如何避免在 c++11 中触发这种复制构造函数?
- 带有C 11继承的构造函数的警告
- 没有C 11的继承构造函数
- 在C++11中按值返回构造的对象时,避免复制构造函数调用
- C++11 cmake O3 选项<没有用于初始化 'std::thread' 的匹配构造函数>
- 为什么 C++11 从 std::vector 的填充构造函数的原型中删除了默认值?