在相同的对象实例(包括子对象)之间使用std::memmove
总是安全的吗?
也就是说,以下对于任何T
和t
是安全的,并且将t
保持不变:
template <typename T>
void maybe_copy(T& t) {
std::memmove(&t, &t, sizeof(T));
}
一个必然的问题是,以下各项始终是安全的:
template <typename T>
void redundant_copy(T& s, const T& d) {
if (std::addressof(s) == std::addressof(d)) {
std::memmove(&d, &s, sizeof(T));
}
}
最佳答案
不,它并不总是安全的。
从https://en.cppreference.com/w/cpp/string/byte/memmove
If the objects are potentially-overlapping or not TriviallyCopyable, the behavior of
memmove
is not specified and may be undefined.
什么是潜在的重叠?
从https://en.cppreference.com/w/cpp/language/object#Subobjects
A subobject is potentially overlapping if it is either
. a base class subobject, or
. a non-static data member declared with the [[no_unique_address]] attribute.
我假设我不需要在此答案中发布TriviallyCopyable的定义。
关于c++ - 是std::memomove在同一对象之间始终是安全的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59852748/