c – 如何防止使用临时调用构造函数
发布时间:2020-12-16 04:58:51 所属栏目:百科 来源:网络整理
导读:我有一个类,其构造函数采用一些向量并存储它们. struct X { X(std::vectorint const ints,std::vectorfloat const floats,std::vectorstd::string const strings) : ints_{ints},floats_{floats},strings_{strings} {}; std::vectorint ints_; std::vectorfl
我有一个类,其构造函数采用一些向量并存储它们.
struct X { X(std::vector<int> const& ints,std::vector<float> const& floats,std::vector<std::string> const& strings) : ints_{ints},floats_{floats},strings_{strings} {}; std::vector<int> ints_; std::vector<float> floats_; std::vector<std::string> strings_; }; 我想将成员变量转换为引用,因为在生产代码中,传递给构造函数的值是左值,其生命周期比类X的对象长. 但是,单元测试通常构造带有临时值的Xes,如下所示: X x{ {42},{3.14f},{"hello"} }; 如果X的成员是引用,则应该阻止这样的调用.这可以通过编写一个构造函数来完成,该构造函数接受rvalue引用并使其= delete. X(std::vector<int> && ints,std::vector<float> && floats,std::vector<std::string> && strings) = delete; 如果所有参数都是临时的,这将阻止实例化.不幸的是,它允许通过调用,其中至少有一个参数是左值: std::vector<std::string> no_strings; X x{ {42},no_strings }; 因为左值引用愿意绑定到rvalues,所以可以调用(const&,const&,const&)构造函数. 我是否必须编写lvalue / rvalue ref参数的所有组合(全部七个)并将它们全部标记为已删除? 解决方法
如果你只是按照图书馆怎么办?
template <typename T> using vector_ref = std::reference_wrapper<std::vector<T> const>; struct X { X(vector_ref<int> ints,vector_ref<float> floats,vector_ref<std::string> strings); }; std :: reference_wrapper已经只能从左值开始构造,所以我们不需要自己完成所有工作. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |