当使用auto并且确定了特定类型时,复制省略的规则是什么?(见:GotW - Almost always auto)。
据我所知,尽管通常不使用移动/复制构造函数,但需要使其可访问。但下面示例中的unique_ptr和fstream有什么区别?(与noexcept有关吗?)
据我所知,尽管通常不使用移动/复制构造函数,但需要使其可访问。但下面示例中的unique_ptr和fstream有什么区别?(与noexcept有关吗?)
#include <memory>
#include <fstream>
int main()
{
auto f = std::fstream{"foo.bar"};
auto i = std::unique_ptr<int>{new int};
return 0;
}
// main.cc:6:10: error: call to implicitly-deleted copy constructor of 'std::basic_fstream<char>'
// auto f = std::fstream{"foo.bar"};
// ^ ~~~~~~~~~~~~~~~~~~~~
auto f = std::fstream{"foo.bar"};
看起来有点傻。直接使用std::fstream f{"foo.bar"};
即可。 - Praetorianauto
是没有意义的。你已经命名了类型,而且auto
也没有什么特别之处,它遵循模板参数推导的规则。唯一的例外是在推导出std::initializer_list
的情况下,但这里并不存在这种情况。 - user3920237