3

考虑以下玩具程序(prog.cpp):

class A {
public:
    vector<int> vec;
    A() noexcept {}
    A(vector<int> s) : vec(s) {}
};

class B {

private:
    vector<atomic<A>> a_table;

public:
    B(int capacity) : a_table(capacity) {}

    void update(int index) {
        A newValue(vector<int>(10,1));
        a_table[index].store(newValue);
    }
};


int main(int argc, char** argv) 
{
B b(5);
b.update(2);
return 0;
}

这在正常编译时(g++ prog.cpp -latomic)工作正常。但是当编译为g++ -fsanitize=address -fno-omit-frame-pointer prog.cpp -latomic执行时会产生 Double Free 错误。基于上述类似行的程序必须在多线程应用程序中使用,即使是正常编译也会产生 Double Free 错误。我阅读了三/五规则,这通常在 Double Free 的情况下被引用,以及各种其他文档,但没有任何效果。

此外,noexceptclass A的默认构造函数中删除说明符会产生这个奇怪的错误,我也想知道。

error: function ‘std::atomic<_Tp>::atomic() [with _Tp = A]’ defaulted on its first declaration with an exception-specification that differs from the implicit declaration ‘std::atomic<A>::atomic()’
   atomic() noexcept = default;
   ^
4

1 回答 1

4

std::atomic需要一个可简单复制的类型,而您A不是,因为它的类型成员vector<int>(例如)不是可简单复制构造的。

自 5.0 版以来,GCC 仅检测到违反该要求的行为。

较旧的 gcc 版本编译代码这一事实并不意味着它是有效的。

于 2016-10-08T20:44:32.360 回答