为什么不能用memcpy复制非POD对象? [英] Why can't non-POD objects be copied with memcpy?

查看:105
本文介绍了为什么不能用memcpy复制非POD对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据我读过的各种资料,以下 C++ 代码调用了未定义的行为:

According to various sources I've read, the following C++ code invokes undefined behaviour:

class A {
public:
    virtual void method () {
        std::cout << "Hello" << std::endl;
    }
};

...
A *a, *b;
// obtain 2 Instances from somewhere, then...
memcpy (a, b, sizeof(A));
a->method();

为什么这会导致未定义的行为?我看不到语言的逻辑实现,它不会像预期的那样运行(在两个对象具有相同运行时类型的情况下),那么为什么语言设计者选择不定义它?

Why does this cause undefined behaviour? I can see no logical implementation of the language where this would not behave as expected (in the case where both objects have the same run-time type), so why did the language designers choose to make this undefined?

推荐答案

为什么这会导致未定义的行为?

Why does this cause undefined behaviour?

因为该语言没有指定多态是如何实现的,因此不能指定多态类型可以简单地复制.

Because the language doesn't specify how polymorphism is implemented, and therefore can't specify that polymorphic types be trivially copyable.

我看不出该语言的逻辑实现不会按预期运行

I can see no logical implementation of the language where this would not behave as expected

多态可以实现为从对象地址到类型信息的映射,而不是存储在每个对象中的指针.人们可能会争论这会更好还是更糟,但这当然不是不合逻辑的.

Polymorphism could be implemented as a map from object addresses to type information, rather than a pointer stored in each object. One might debate whether that would be better or worse, but it's certainly not illogical.

为什么语言设计者选择不定义它?

why did the language designers choose to make this undefined?

以免限制提出更好的多态性实现的可能性.您看不到替代品并不一定意味着它们不存在.

So as not to constrain the possibility of coming up with better implementations of polymorphism. Your inability to see alternatives doesn't necessarily mean that they don't exist.

这篇关于为什么不能用memcpy复制非POD对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆