Why does std::function::operator= in C++ always construct and not assign object?
This query is mainly based on std::function<R(Args...) >::operator=
and std::any::operator=
. The documentation shows that they are always implemented by constructing a new temporary object and swapping it with this object using the swap function, which is equivalent to destructing 开发者_如何学JAVAthe retained object and calling the construction operation of the retained object (T(T)
) to construct a new object. And std::variable<Types... >::operator=
calls the assignment of the retained object (operator=(T)
) when the LHS and RHS have the same object. The question is, why does std::function<R(Args...) >::operator=
and std::any::operator=
destruct the original object and construct the new object via a constructor operation, regardless of whether the new object is the same as the retained object? Wouldn't it be better to construct by assignment than by destructuring?
I have checked the documentation and searched many web pages and did not find a detailed explanation, it seems that everyone does this by convention. I would like to know the reason for using swap to handle assignment operations when implementing std::any
and std::function
with small object optimizations, and its best practice.
精彩评论