• 10
• 10
• 12
• 12
• 14

# help passing class into std::thread arguments

This topic is 916 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

See code snippet below:

class A {
public:
A() {
std::cout << "A is constructed" << std::endl;
}

~A() {
std::cout << "A is destroyed" << std::endl;
}
};

static void foo( A a ) {
std::cout << "inside foo" << std::endl;
}

int _tmain(int argc, _TCHAR* argv[]) {
A a;

return 0;
}

The console output that I see is:

A is constructed
inside foo
A is destroyed
A is destroyed
A is destroyed
A is destroyed
A is destroyed
A is destroyed
Press any key to continue . . .

I create an instance of A and then try to pass it into a new thread.  I pause my main thread for 2 seconds and then I quit.  Why is the A destructor called so many times, but the constructor is only called once?

I should mention that I'm using VS2013 on Windows 7.

Edited by MarekKnows.com

##### Share on other sites
It appears that you're passing your As by value. At least some of the extra destructor invocations come from the copies being destroyed. If you were to define a copy constructor that logged the way your constructor does, you would see the copies being created as well as destroyed.

##### Share on other sites

Yup. More specifically, your class actually looks like:

class A {
public:
A() {
std::cout << "A is constructed" << std::endl;
}

// Copy constructor generated automatically by compiler
A(const A &a) {
}

~A() {
std::cout << "A is destroyed" << std::endl;
}
};