A brief analysis of static_cast to convert lvalue to rvalue

Written in cppreference:

“If conversion of expression to new-type involves lvalue-to-rvalue, array-to-pointer, or function-to-pointer conversion, it can be performed explicitly by static_cast.”

This shows that we can use static_cast to convert lvalues ​​to rvalues. You may think of std::move. Isn’t this also converting lvalues ​​to rvalues? What’s the difference between the two?

 

This shows that because our std::move is implemented using templates, it is much more convenient to use than static_cast. 

Let's take a look at the internal implementation of `std::remove`:

As you can see, first of all, the function parameters are of type T&&, so that any lvalue or rvalue can be matched through reference folding.

Then use remove_reference to remove all references to T, and add &&, so that no matter what type T is, it becomes an rvalue reference type, and then use static_cast to convert t into our rvalue reference.

In other words, the function of std::move is to use static_cast to explicitly convert T, T&, T&& all into T&&.

In fact, when talking about static_cast, we have to mention the unsafety of its conversion.

References:

(37 messages) C++11 new features (66) - Use static_cast to convert lvalues ​​to rvalues_Object-oriented thinking blog-CSDN blog  C++ explicit conversion (1)-static_cast (qq.com)

https://en.cppreference.com/w/cpp/language/static_cast

Guess you like

Origin blog.csdn.net/qq_55621259/article/details/129968887