This seems to be the most common question that has already been asked.
What is the difference between std :: move and std :: forward
But each answer is different and applied and says slightly different things. Therefore, I am confused.
I have the following situation.
- Copy item to container
The Copy element is C ++ 03, so I understand it well. - Construct an item in a container
The Construct element in the container, which I suppose uses the correct forwarding correctly to redirect the arguments with two functions to the T constructor in emplaceBackInternal()
(say differently if I am wrong). - Move item to container
My problem seems to be understanding the movement of an element in a container.
Code:
template<typename T> class Container { std::size_t length; T* buffer; public: void push_back(T const& value) { resizeIfRequired(); pushBackInternal(value); } template<typename... Args> void emplace_back(Args&&... args) { resizeIfRequired(); emplaceBackInternal(std::forward<T>(arg)...); } void push_back(T&& value) { resizeIfRequired();
I include all three here to compare the three functions with the answers given in the above answer. The main reason is because move
and construct
look so similar that they seem to be the same.
Reply @Potatoswatter Score 67
std :: forward has one use case: for adding the templated function parameter
By this definition, I have to use std::move
inside push_back(T&& value)
and moveBackInternal(T&& value)
, since the value is not a template parameter for the function.
Reply @Howard Hinnant Score 38
If Y is a reference to an lvalue, the result is an lvalue expression. If Y is not an lvalue reference, the result will be an rvalue expression (xvalue to exact value).
By this definition, I can use either std::move
or std::forward
.
Reply @Bo Persson Score 11
std :: forward is used to forward the parameter exactly as it was passed to the function.
It seems that std::forward
valid (although if I follow the link in the answer, all examples use template functions).