To answer my own question - I was missing the join the synchronized the main thread with the child one.
Once I had added that, the second temporary got deleted (but only at the point of the join).
So, here's the amended program:
// ThreadTest.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <sstream>
#include <thread>
#include <mutex>
void log(std::string & message) {
static std::mutex logMutex;
// Lock the log mutex to prevent overlapped log I/O.
std::lock_guard<std::mutex> log_lock(logMutex);
std::cout << message;
}
class MyObject {
public:
MyObject(void) : data(0) {
std::ostringstream message;
message << __FUNCTION__ << " called. this=" << this << ".\n";
log(message.str());
}
MyObject(const MyObject & source) {
std::ostringstream message;
message << __FUNCTION__ << " called. this=" << this << ", source=" << &source << ".\n";
log(message.str());
this->data = source.data;
}
~MyObject(void) {
std::ostringstream message;
message << __FUNCTION__ << " called. this=" << this << ".\n";
log(message.str());
}
MyObject & operator=(const MyObject & source) {
std::ostringstream message;
message << __FUNCTION__ << " called. this=" << this << ", source=" << &source << ".\n";
log(message.str());
this->data = source.data;
}
int data;
};
void threadTest(MyObject myObject) {
std::cout << __FUNCTION__ << ": myObject is at " << &myObject << ".\n";
}
int _tmain(int argc, _TCHAR* argv[])
{
std::ostringstream message;
MyObject myObject;
myObject.data = 1;
message << __FUNCTION__ << ": myObject is at " << &myObject << ".\n";
log(message.str());
std::thread myThread(threadTest, myObject);
myThread.join();
return 0;
}
and the new results:
MyObject::MyObject called. this=0012FECC.
wmain: myObject is at 0012FECC.
MyObject::MyObject called. this=0012FDA0, source=0012FECC.
MyObject::MyObject called. this=0052FFF4, source=0012FDA0.
MyObject::~MyObject called. this=0012FDA0.
MyObject::MyObject called. this=0052FC80, source=0052FFF4.
threadTest: myObject is at 0052FC80.
MyObject::~MyObject called. this=0052FC80.
MyObject::~MyObject called. this=0052FFF4.
MyObject::~MyObject called. this=0012FECC.
Sometimes, all it takes is to simplify the problem and to try to explain it...