#Use after move with std::forward

1 messages · Page 1 of 1 (latest)

dawn dust
#

I'm looking at the following piece of code written by a colleague.

template <size_t N> struct Apply {
  template <typename F, typename T> static FORCE_INLINE void apply(F &&f, T &&t) {
    Apply<N - 1>::apply(::std::forward<F>(f), ::std::forward<T>(t));
    ::std::forward<F>(f)(::std::get<N>(::std::forward<T>(t)));
  }
};

Am I correct in thinking that there is a use after move of f here?

viral lake
#

yes, this is almost certainly wrong

#

you can't really forward the same thing twice

dawn dust
#

This code was being used for essentially, applying a functor f(x) for each entry in a tuple. I've not used std::apply before, but I thought this would do the job to replace it

template <typename Function, typename Tuple>
constexpr void apply(Function &&f, Tuple &&t) {
  std::apply([&f](auto &&...x) { (f(x), ...); }, std::forward<Tuple>(t));
}

Any gotcha I need to be aware of here?

viral lake
#

I mean, lgtm. just not sure why this would exist. looks like you might as well just use std::apply instead of this?

#

the only difference i see between this and std::apply is that this one returns void

dawn dust
viral lake
#

ah because this one applies the function to each element

#

gotcha

dawn dust
#

yep

upbeat dome
viral lake
#

because the first forward might result in a move, then what?

upbeat dome
#

hmmmmm

feral prawn
viral lake
#

forwarding the same thing more than once is pretty much never not a bug

upbeat dome
#

somehow i never considered this

#

now i have to rethink all of my code again

viral lake
#

yeah, i also often didn't ^^

upbeat dome
#

when are forward references useful then?

viral lake
#

when you want to perfectly just forward a thing

upbeat dome
#

why would i need to do that

viral lake
#

forward meaning immediately hand it off to the next guy

viral lake
#

the purpose of std::forward is to forward a thing in a way that preserves the value category of the original thing.

upbeat dome
viral lake
#

probably

#

it's only use is perfect forwarding

upbeat dome
#

i see