c++ why is copy constructor called twice (capture class instance by value to lambda)

  softwareengineering
#include <iostream>
#include <thread>


class MyClass
{
public:
    MyClass(int _x, int _y) : x(_x), y(_y) {}

    // Copy constructor
    MyClass(const MyClass &other) : x(other.x), y(other.y)
    {
        std::cout << "Copy constructor called" << std::endl;
    }

    int x;
    int y;
};


int main()
{

    MyClass myclass(42, 84);

    std::thread thread([myclass] () {});
    thread.join();

    return 0;
}

In this example, “Copy constructor called” is printed twice to the screen. I understand that myclass is passsed by value to the lambda, hence a copy is created. But I do not understand why the copy constructor is called a second time.

New contributor

Simon is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

2

LEAVE A COMMENT