为什么 boost::atomic 支持非平凡可复制对象?

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

boost::atomic 要求 T 可以轻松复制。但为什么下面的

boost::atomic<atom>
代码有效呢?


#include <chrono>
#include <iostream>
#include <memory>
#include <unordered_set>
#include <parallel/algorithm>
#include <boost/algorithm/cxx11/all_of.hpp>
#include <boost/atomic.hpp>
#include <boost/optional/optional.hpp>
#include <boost/range/algorithm/copy.hpp>
#include <boost/range/algorithm/count_if.hpp>
#include <boost/range/algorithm/remove_if.hpp>
#include <boost/range/algorithm/sort.hpp>
#include <boost/range/algorithm/unique.hpp>
#include <boost/range/irange.hpp>
#include <boost/range/numeric.hpp>


typedef uint32_t vint;  // Integer for vertex IDs

constexpr vint vmax = std::numeric_limits<vint>::max();  // Used as invalid ID

struct atom {
  boost::atomic<float> str;    // Total weighted degree of the community members
  boost::atomic<vint>  child;  // Last vertex that is merged to this vertex
  std::string c;
};

struct vertex {
  boost::atomic<atom> a;
  boost::atomic<vint> sibling;
  vint         united_child;
};

int main() {
    std::cout << "Is 'atom' trivially copyable? " 
              << std::boolalpha 
              << std::is_trivially_copyable<atom>::value
              << std::endl;

    return 0;
}

参考:https://godbolt.org/z/vEv4jreK9

c++ boost stdatomic
1个回答
1
投票

如果您没有陷入 C++98 或 C++03 的困境,那么就没有理由使用

boost::atomic
。 C++11 添加了与
std::atomic
中的
<atomic>
相同的标准化功能。

如果您使用的是 C++98 或 C++03,则无法在编译时检查类型是否可简单复制。必要的类型特征只是在 C++11 中添加的,不可能用 C++ 核心语言功能来实现。

因此,在这种情况下,模板无法在编译时告诉您您给它的类型是不允许的。你只会导致未定义的行为。检查该类型是否可简单复制就是您的责任。

您确实应该升级到 C++11 或更高版本。与许多其他语言相比,这只是旧 C++ 语言的一个小缺点。

© www.soinside.com 2019 - 2024. All rights reserved.