首页 > 解决方案 > 为什么 C++ 允许返回 ifstream 对象?

问题描述

在 C++98 中,以下代码无法编译,因为 ifstream 没有复制构造函数:

#include <iostream>
#include <fstream>
using namespace std;

ifstream f() {
    return ifstream("main.cpp");
}

int main() {
    ifstream st= f();
}

但是,在 C++11 中使用多个 GCC 版本,编译时不会出现警告。这是什么原因?

标签: c++c++11fstreamxvalue

解决方案


C++11 添加了移动构造函数。流现在已移动。st这里的源对象是返回表达式中的一个临时对象,可以移动到main.


推荐阅读