16

I understand that auto means type deduction. I've never seen it used as auto& and furthermore I don't understand what : is doing in this short code.

#include <iostream>
#include <vector>
#include <thread>

void PrintMe() {
    std::cout << "Hello from thread: " << std::this_thread::get_id() << std::endl;
}

int main() {
    std::vector<std::thread> threads;
    for(unsigned int i = 0; i < 5; i++) {
        threads.push_back(std::thread(PrintMe));
    }

    for(auto& thread : threads) {
        thread.join();
    }

    return 0;
}

I can guess this is some sort of syntatic sugar that replaces

for(std::vector<std::thread>::iterator it = threads.begin(); it != threads.end(); it++ ) {
    (*it).join();
}

but I don't understand how this syntax works and what that & sign is doing there.

6
  • 2
    It's a range-based for and a reference.
    – chris
    Oct 16 '13 at 21:32
  • 3
    Aww, that (*) operator! Should've been written as it->join();...
    – user529758
    Oct 16 '13 at 21:33
  • 1
    @H2CO3 would have but I was trying to make it more like the original loop with .join() ;) Hehehe.
    – Chemistpp
    Oct 16 '13 at 21:33
  • 1
    Seems like a moot point. Why?
    – Chemistpp
    Oct 20 '13 at 21:27
28

You are almost correct with your sample code.

Auto meaning was redefined in C++11. The compiler will inferer the right type of the variable that is being used.

The syntax with : it's a range based for. It means that loop will parse each element inside threads vector.

Inside the for, you need to specify the alias auto& in order to avoid creating a copy of the elements inside the vector within the thread variable. In this way every operation done on the thread var is done on the element inside the threads vector. Moreover, in a range-based for, you always want to use a reference & for performance reasons.

2
  • 3
    auto was not introduced in C++11. It only had its meaning re-defined.
    – user529758
    Oct 16 '13 at 21:34
  • Okay!! Thank you for your answer! I'd accept it already but it says I have to wait. I compiled without & (and of course it failed because of thread) but I see what the difference is now.
    – Chemistpp
    Oct 16 '13 at 21:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.