多线程程序中的临时对象问题:链式操作下的对象定义疑问
Alright, let's break this down step by step—starting with fixing that sum function's temporary object definition, then diving into the critical thread-safety rules you need to follow.
1. First: Fixing the Temporary Object in Your sum Function
Right now, your sum function is missing the actual creation of the myclass object c. The correct way to define this temporary object is straightforward:
myclass sum(myclass* a, myclass* b) { // Create a local temporary object using your default constructor myclass c; // Set its values using the getters from a and b c.set_longitude(a->get_longitude() + b->get_longitude()); c.set_latitude(a->get_latitude() + b->get_latitude()); // Return the temporary object—compilers will usually optimize this with RVO (Return Value Optimization) return c; }
If you add a parameterized constructor to myclass (which is a good practice for clarity), you can make this even more concise:
// Add this to your myclass public section: myclass(int lat, int lon) : latitude(lat), longitude(lon) {} // Then rewrite sum: myclass sum(myclass* a, myclass* b) { return myclass( a->get_latitude() + b->get_latitude(), a->get_longitude() + b->get_longitude() ); }
The RVO optimization I mentioned is key here—it lets the compiler construct the returned object directly in the caller's stack space, skipping any unnecessary copy operations. This is totally safe and standard in C++.
2. Thread-Safety Rules for Temporary Objects
Now, let's get to the multi-threaded scenario. Here are the non-negotiable rules you need to follow:
Temporary objects are thread-safe by default—if you don't leak their address/reference to other threads
The temporarycin yoursumfunction lives in the stack space of the thread callingsum. Each thread has its own isolated stack, so no other thread can access this object unless you explicitly pass a pointer or reference to it. As long as you don't do something silly likereturn &c;(returning a pointer to a temporary that will be destroyed immediately), you're good here.If you pass a temporary to another thread, ensure it outlives the thread's execution
This is the most common pitfall. For example, this code is dangerous:// BAD: The temporary temp is destroyed when bad_example() exits, but the thread might still be running void bad_example(myclass a, myclass b) { auto temp = sum(&a, &b); std::thread t(anotherfunc, std::ref(temp)); t.detach(); // Thread runs independently—temp is gone when this function ends }Instead, use one of these safe approaches:
- Pass a copy of the temporary to the thread, so the thread gets its own independent instance:
void safe_example1(myclass a, myclass b) { auto temp = sum(&a, &b); std::thread t(anotherfunc, temp); // Copies temp into the thread's stack t.join(); // Wait for thread to finish before temp goes out of scope (though even if you didn't, the copy is safe) } - Move the temporary to heap storage (managed by smart pointers) to extend its life:
void safe_example2(myclass a, myclass b) { auto obj_ptr = std::make_unique<myclass>(sum(&a, &b)); std::thread t(anotherfunc, std::move(obj_ptr)); // Transfer ownership to the thread t.join(); }
- Pass a copy of the temporary to the thread, so the thread gets its own independent instance:
If multiple threads share the same object (even a former temporary), use synchronization
If you need multiple threads to read/write the samemyclassinstance, you must protect its state with a mutex or atomic variables. For example, ifanotherfuncmodifies the object's values:#include <mutex> std::mutex obj_mutex; // Global or member mutex, depending on your use case int anotherfunc(myclass obj) { std::lock_guard<std::mutex> lock(obj_mutex); // Locks for the duration of this scope obj.set_latitude(obj.get_latitude() + 1); return obj.get_latitude(); }That said, if you're passing copies to each thread (like in
safe_example1), synchronization isn't needed—each thread works on its own copy, which is far more efficient.Don't fight compiler optimizations like RVO
RVO is a standard, safe optimization that eliminates unnecessary copies. It doesn't introduce thread-safety issues because the optimized object still lives in the caller's thread stack. You don't need to disable it or work around it—embrace it for better performance.
3. Bonus: Optimize with Move Semantics
If your myclass ever grows beyond small int members (e.g., adding large strings or arrays), adding move semantics will make your chained operations even more efficient. Here's how to update your class:
class myclass { public: // Default constructor myclass() : latitude(0), longitude(0) {} // Parameterized constructor myclass(int lat, int lon) : latitude(lat), longitude(lon) {} // Move constructor (noexcept is important for optimizations) myclass(myclass&& other) noexcept : latitude(std::move(other.latitude)), longitude(std::move(other.longitude)) {} // Move assignment operator myclass& operator=(myclass&& other) noexcept { if (this != &other) { latitude = std::move(other.latitude); longitude = std::move(other.longitude); } return *this; } // Getters and setters (keep these as is) void set_latitude(int lat) { latitude = lat; } int get_latitude() const { return latitude; } void set_longitude(int lon) { longitude = lon; } int get_longitude() const { return longitude; } private: int latitude; int longitude; };
When you return a temporary object now, the compiler will use the move constructor instead of copying the object—this is faster and still thread-safe, as long as you don't move an object that's being accessed by another thread.
内容的提问来源于stack exchange,提问作者Podarce

