GCC 8无法编译make_shared ()

问题描述 投票:3回答:1

这段代码编译干净,适用于我尝试过的所有编译器,除了GCC 8(和当前的GCC主干):

std::make_shared<volatile int>(0)

我想知道:

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

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

c++ c++11 gcc volatile make-shared
1个回答
5
投票

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

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

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)...);
}
© www.soinside.com 2019 - 2024. All rights reserved.