在C++中,返回值是否保证在函数内的自动变量被销毁之前创建?请注意Basket::get:
class Basket
{
public:
// Gift is a struct containing safely copyable things like int or string
Gift gift;
// Used to protect access and changes to gift
Mutex mutex;
// Copy gift into present, while locked to be thread safe
void put (const Gift & gift)
{
Lock lock(mutex); // Constructor locks, destructor unlocks mutex
this->gift = gift; // Gift assignment operator
}
// Return a memberwise-copy of gift, tries to be thread safe (but is it?)
Gift get ()
{
Lock lock(mutex); // Constructor locks, destructor unlocks mutex
return gift; // Gift copy constructor
}
};
我希望Basket::get在锁对象被销毁之前执行其Gift复制构造函数(返回的临时对象)以避免由于对put的同时调用而导致返回的gift对象被破坏。
我的测试表明,Gift的拷贝确实是在锁被销毁之前创建的,但这是否有保证呢?如果没有,我需要在函数内部创建第二个临时对象,例如:
Gift get ()
{
Gift result;
{
Lock lock(mutex);
result = gift;
}
return result;
}