3

这段代码可以干净地编译,并且可以与我尝试过的所有编译器一起使用,除了 GCC 8(和当前的 GCC 主干):

std::make_shared<volatile int>(0)

我想知道:

  1. GCC 8 拒绝此代码是否正确?
  2. 是否有 GCC 8 将接受的替代品(具有相同的语义和性能)?我知道std::atomic,但语义不一样,所以建议使用它而不是volatile我想要的。

在这里看到它:https ://godbolt.org/z/rKy3od

4

1 回答 1

5

根据标准语言,这是不符合 libstdc++ 的。

这可能是一个错误。make_shared使用标准分配器调用allocate_sharedstd::allocator<remove_const_t<T>>其中T是共享对象的类型。此分配器将仅用于为底层共享对象(包含 volatile int 和原子计数器的结构)获取重新绑定的分配器。因此,将这个底层对象声明为非 const 非易失性是完全可以的。

这个定义make_shared将起作用:

template<class T,class...Args>
auto make_shared(Args&&...args){
    using ncvT= std::remove_cv_t<T>;
    return std::allocate_shared<T>(std::allocator<ncvT>(),std::forward<Args>(args)...);
}
于 2018-09-11T07:27:31.157 回答