【发布时间】:2018-08-22 09:17:23
【问题描述】:
编辑: this 似乎完美地解决了我的问题。
关于Which type trait would indicate that type is memcpy assignable? (tuple, pair)
答案是std::is_trivially_copyable 可以告诉我我是否可以安全地memcpy 在我的对象周围。
现在考虑:
#include <iostream>
#include <type_traits>
struct A {
int x;
int y;
A(const A& other) : x(other.x), y(other.y){}
};
struct B {
int x;
int y;
B(const B& other) = default;
};
int main()
{
std::cout << std::boolalpha;
std::cout << std::is_trivially_copyable<A>::value << '\n'; //false
std::cout << std::is_trivially_copyable<B>::value << '\n'; //true
}
A 和 B 在实际效果上都是相同的,但是 A 被检测为不可轻易复制。
那么,在memcpy-ing 这样的对象中,我会承担哪些风险?
用例:我想在 opencv 库中有一个cv::Point 的动态数组(不是vector,我会用realloc 使其增长),这可能是因为 C++98 兼容性不'不要使用default 来定义复制构造函数。
【问题讨论】:
-
如果类型的复制构造函数确实只是复制字节,编译器无论如何都会知道将其优化为
memcpy。不要出汗。 -
@Brian 查看编辑:我的精确用例是
cv::Point的数组,我将在其中使用 realloc(我知道当std::is_trivially_copyable通过时,对std::is_trivially_destructible的检查变得多余)跨度> -
当默认的复制构造函数会这样做时,你为什么要 memcpy 对象?
-
@NeilButterworth 如果我想将
cv::Point的一个数组复制到另一个数组中(假设我有充分的理由不使用std::vector) -
@Antonio:我认为 Neil 的观点是
std::copy将为您隐式调用默认的复制构造函数,那么为什么不直接这样做而不是测试定义行为的限制呢?std::copy(&src[0], &src[len], &dst[0])或std::copy_n(&src[0], len, &dst[0])在某种程度上比memcpy(&dst[0], &src[0], len * sizeof(src[0]))差吗?
标签: c++ opencv c++11 opencv3.0 memcpy