Sau*_*abh 7 c++ compiler-construction destructor
可以说我有两个本地对象.当函数返回时,是否保证哪一个将首先超出范围?
例如:
我有一个这样的课:
class MutexLock
{
/* Automatic unlocking when MutexLock leaves a scope */
public:
MutexLock (Mutex &m) { M.lock(); }
~MutexLock(Mutex &m) { M.unlock(); }
};
Run Code Online (Sandbox Code Playgroud)
这是一个非常常见的技巧,用于在超出范围时自动释放互斥锁.但是如果我在范围内需要两个互斥量呢?
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?
Run Code Online (Sandbox Code Playgroud)
这真的不会造成任何僵局.但是可能存在释放资源的顺序对用户有用的实例.在这种情况下,重要的是要明确而不是依赖于析构函数?
此外,编译器在任何情况下都可以延迟销毁吗?我的意思是
func()
{
{
foo f();
} ---------> Can compiler choose to not destroy f here, rather do it at the time when func() is returning.
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
489 次 |
| 最近记录: |