Why can't std::as_const(T &&v) move-return its argument?

倖福魔咒の 提交于 2021-01-21 09:18:21

问题


Reading Why does as_const forbid rvalue arguments? I understand that we can't convert a rvalue-ref into an lvalue-ref, of course.

But why not move the rvalue-ref into a value and return that, i.e. ?

template<typename T> 
const T as_const(T&& val) { return std::move(val); } 

This ought to work nicely with COW containers as well, as the returned value is const and iterators from it will not cause it to detach.

Maybe some godbolt-ing will answer this though, but I can't think of a given scenario and there are no COW containers easily available there AFAIK.

Update:

Consider this COW container (ignoring threading issues):

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); 
   }
   ...
};

Move would be fast and the const T returned would select the const-version of begin() when used in range-for-loop.

There are also containers that mark themselves as modified so their changes can be sent over network or later synced to another copy (for use in another thread), f.ex. in OpenSG.


回答1:


I understand it as an additional feature to have but to avoid some measuses: get a const view to something which has an address.

And because a temporary does not have an address, there should also be no const view of it.

And moving the value rather than just adding const would change it's semantics ( we already have std::move)

And if as_const to a temporary would extend it's lifetime on it's own, then it would waste space if not bound, for example:

{
   as_const(f()); // if the lifetime would be extended
...
 } // not bound, but space wasted

For example as_const adds const to a value rather than to a type, so it's saving some typing like static_cast, add_const etc.

Normaly binding a const lvalue ref to a temporary, would extend the temporary lifetime, for example:

int f() { return 3; }

{
   const auto& x = f();
    ... use x .. ok
}

But something like this would end to a dangling reference:

{
   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/why-cant-stdas-constt-v-move-return-its-argument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!