简体   繁体   中英

Function pointers in C++ syntax

I inspected the signature of this right part of this assignment: creating a thread:

std::thread t2 = std::thread(&Vehicle::addID, &v2, 2);

by hovering with the mouse on and "thread" on the right I got:

std::thread::thread<...>(void (Vehicle::*&&_Fx)(int id), Vehicle &_Ax, int &&_Ax)

Now, I know the basics of C function pointers syntax.

But in C++ you see many times first the class name on the left (especially when using templates)

so I understand that - * within this syntax means a pointer to a (public) member function of the class Vehicle that take an int and returns void (nothing), but whats the && (similar to move constructor) mean? reference to reference of / take the reference to the member function object by reference??

Notice how the lvalue argument ( &v2 ) becomes an lvalue reference, and the rvalue arguments (the literal 2 and your &Vehicle::addID ) become an rvalue reference.

The constructor template you're using is:

template< class Function, class... Args >
explicit thread( Function&& f, Args&&... args );
//                                 ^^

We can see there that we ask the computer to take the arguments by "universal reference", ie as referency as possible, given each one's value category.

So you're seeing the result of that.

It's not part of the type of the pointer-to-member-function: it's something that's become an rvalue-reference-to-pointer-to-member-function because that's how std::thread takes its arguments, for the purpose of being nice and generic. In the case of a function pointer it's redundant, as there's nothing to "move", but for more complex arguments this can be important.

Of course, due to the nasty "spiral rule" we inherited from C, you end up with the && confusingly plonked in the middle of the pointer's type. 🤪😭


tl;dr:

take the reference [pointer — Ed. ] to the member function object by reference??

Pretty much.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM