阅读Why does as_const forbid rvalue arguments?,我明白我们不能将rvalue-ref转换为lvalue-ref,当然。
但是为什么不将rvalue-ref移动到一个值中并返回它,即?
template<typename T>
const T as_const(T&& val) { return std::move(val); } 这也应该与COW容器很好地工作,因为返回的值是const,迭代器不会导致它分离。
也许一些上帝会回答这个问题,但我想不出一个特定的场景,而且在AFAIK中也没有很容易获得的奶牛容器。
更新:
考虑一下这个牛容器(忽略线程问题):
class mything {
std::shared_ptr<std::vector<int>> _contents;
auto begin() { if (_contents.use_count() > 1) { detach(); }
return _contents->begin(); }
auto begin() const { return _contents->begin(); }
void detach() {
_contents = std::make_shared<decltype(_contents)>(*_contents);
}
...
};移动速度很快,返回的const T将在range for-循环中使用时选择begin()的const版本。
还有一些容器将自己标记为已修改,这样它们的更改就可以通过网络发送或稍后同步到另一个副本(用于另一个线程),f.ex。在OpenSG中。
发布于 2021-01-14 10:27:08
我认为这是一个额外的特性,但要避免一些措施:获得一个具有地址的内容的const视图。
而且,由于临时地址没有地址,因此也不应该有const视图。
移动值而不是仅仅添加const将改变它的语义(我们已经有了std::move)
如果一个临时的as_const会延长它自己的生存期,那么如果不绑定它就会浪费空间,例如:
{
as_const(f()); // if the lifetime would be extended
...
} // not bound, but space wasted例如,as_const将const添加到值,而不是类型,因此它保存了一些类型,如static_cast、add_const等。
将const lvalue ref绑定到临时的Normaly将延长临时生存期,例如:
int f() { return 3; }
{
const auto& x = f();
... use x .. ok
}但是像这样的东西最终会变成一个悬空的引用:
{
auto& x = as_const(f()); // one could wrongly think that temporary lifetime is extended, but it's not
... x dangles ..
}https://stackoverflow.com/questions/65716682
复制相似问题