我有一个类,其构造函数采用一些向量并存储它们.
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_;
};
Run Code Online (Sandbox Code Playgroud)
我想将成员变量转换为引用,因为在生产代码中,传递给构造函数的值是左值,其生命周期比类X的对象长.
但是,单元测试通常X用临时构造es,如下所示:
X x{ {42}, {3.14f}, {"hello"} };
Run Code Online (Sandbox Code Playgroud)
如果X要引用成员,则应阻止此类调用.这可以通过编写一个构造函数来完成,该构造函数接受rvalue引用并制作它=delete.
X(std::vector<int> && ints, std::vector<float> && floats, std::vector<std::string> && strings) = delete;
Run Code Online (Sandbox Code Playgroud)
如果所有参数都是临时的,这将阻止实例化.不幸的是,它允许通过调用,其中至少有一个参数是左值:
std::vector<std::string> no_strings;
X x{ {42}, {3.14f}, no_strings };
Run Code Online (Sandbox Code Playgroud)
因为左值引用愿意绑定到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);
};
Run Code Online (Sandbox Code Playgroud)
std::reference_wrapper已经只能从左值构造,所以我们不需要自己做所有这些工作。
| 归档时间: |
|
| 查看次数: |
267 次 |
| 最近记录: |