Search code examples
c++multithreadingvisual-studio-2013copy-constructorstdthread

Copy constructor calls when creating a new thread


I'm reading the book C++ Concurrency in Action to learn more about threading and the C++ memory module. I'm curious about the number of times the copy constructor is called in the following code:

struct func
{
    func() = default;
    func(const func& _f) {}

    void operator()() {}
};

int main()
{
    func f;
    std::thread t{ f };
    t.join();

    return 0;
}

When I walk through this code in the Visual Studio 2013 debugger, I see the copy-constructor called four separate times. It's called three times from the main thread and then once from the new one. I was expecting one, as it made a copy of the object for the new thread. Why are three extra copies created?


Solution

  • If you set breakpoint in copy constructor you can see constructor call context in Call Stack window. In debug mode i found next points when constructor is called:

    • First off the functional object is copied in helper function bind

    • Then the functional object is moved into a internal functional object _Bind

    • After that a class for launching threads _LaunchPad is created. In
      a constructor it takes rvalue reference to the _Bind instance so we have
      another one move constructor call

    • move constructor of _LaunchPad is called when copy of it is created in new thread.

    Thus we have 4 copy constructor call in your case. If you added move constructor you would see 1 copy constructor and 3 move constructor calls.

    In release mode all empty constructor calls is elided and assembler code looks quite simple