相关疑难解决方法(0)

基于堆栈的RAII是否只能在超出C++范围后才能运行?

在C++中使用资源获取初始化(RIAA)时,通常会有以下内容:

class CriticalSection {
public:
    void enter();
    void leave();
};

class SectionLocker {
public:
    SectionLocker(CriticalSection& cs)
    : mCs(cs) {
       cs.enter();   
    }

    ~SectionLocker() {
        cs.leave();
    }

private:
    CriticalSection& mCs;
};

CriticalSection gOperationLock; // Global lock for some shared resource

void doThings(int a, int b) {
    SectionLocker locker(gOperationLock);
    int c = doOtherThings(a);
    doMoreThings(b);
    doOneMoreThing(a, b, c);
}
Run Code Online (Sandbox Code Playgroud)

我知道在一些垃圾收集语言(例如CLR)中,为什么这不安全的众多原因之一是doThings()内的locker对象在doThings()返回之前有资格进行垃圾收集,因为locker永远不会创建后引用.

只有在调用doOneMoreThing()之后才调用析构函数的析构函数,这是C++中明确定义的行为吗?

如果是这样,是否有任何关于何时调用析构函数(并释放gOperationLock)的保证?或者仅仅是在它超出范围之后的某个时刻?

c++ concurrency

3
推荐指数
1
解决办法
185
查看次数

标签 统计

c++ ×1

concurrency ×1