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.
const
on a return value (not reference) is basically meaningless – Hypnotismstd::move(val)
asT
will make a copy ofval
in any case. Furthermore,return std::move(...)
is an anti-pattern that often prohibits NRVO. However, even NRVO won't help when returning an input argument, there will always be copying involved. – Dhustd::move
that anything is actually moved. – Raila