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;
}
Run Code Online (Sandbox Code Playgroud)
参考: https: //godbolt.org/z/vEv4jreK9
如果您没有陷入 C++98 或 C++03 的困境,那么就没有理由使用boost::atomic. std::atomicC++11 添加了与<atomic>.
如果您使用 C++98 或 C++03,则无法在编译时检查类型是否可简单复制。必要的类型特征只是在C++11中添加的,不可能用C++核心语言功能来实现它。
因此,在这种情况下,模板无法在编译时告诉您您给它的类型是不允许的。你只会导致未定义的行为。检查该类型是否可简单复制是您的责任。
您确实应该升级到 C++11 或更高版本。与许多其他语言相比,这只是旧 C++ 语言的一个小缺点。
但是,我刚刚注意到您正在使用一些 C++11 或更高版本的功能。所以我很困惑你为什么要尝试使用boost::atomic.
此外,如果您在 C++11 或更高版本的模式下编译,boost 通常应该在编译时检查该类型是否可简单复制。但是,您也在使用旧版本的 boost。编译时检查在 1.68 中尚未实现(大概是因为在 C++11 模式下没有太多使用boost::atomic)。它是通过版本 1.73 的此提交实现的。