【发布时间】:2012-05-22 15:25:51
【问题描述】:
假设我有两个本地对象。函数返回时,是否保证哪个会先出作用域?
例如:
我有这样的课:
class MutexLock
{
/* Automatic unlocking when MutexLock leaves a scope */
public:
MutexLock (Mutex &m) { M.lock(); }
~MutexLock(Mutex &m) { M.unlock(); }
};
这是一个非常常见的技巧,用于在超出范围时自动释放互斥锁。但是,如果我需要在作用域中使用两个互斥锁怎么办?
void *func(void *arg)
{
MutexLock m1;
MutexLock m2;
do_work();
} // m1 and m2 will get unlocked here. But in what order? m1 first or m2 first?
这确实不会导致任何死锁。但在某些情况下,释放资源的顺序可能对用户有用。在这种情况下,显式而不是依赖析构函数重要吗?
另外,编译器在任何情况下都可以延迟销毁吗?我的意思是
func()
{
{
foo f();
} ---------> Can compiler choose to not destroy f here, rather do it at the time when func() is returning.
}
【问题讨论】:
标签: c++ compiler-construction destructor