You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在C++中逐字节覆盖内存中的多态对象是否合法?

用memcpy修改多态对象的类型是否可行?

这是一个假设性问题而非实际问题:假设我通过分配器始终为最大对象预留足够空间的方式分配多态对象,想了解是否可以使用memcpy将一个多态对象的类型改为另一种。

以下是我随手编写的未测试代码:

class Animal {
  virtual ~Animal() {}
};

struct Cat : public Animal {
  int lives;
};

struct Dog : public Animal {
  size_t bark_count;
};

Dog* dog = static_cast<Dog*>(malloc(std::max(sizeof(Dog), sizeof(Cat))));
new (dog) Dog(0);

Cat* cat = static_cast<Cat*>(malloc(std::max(sizeof(Dog), sizeof(Cat))));
new (cat) Cat(9);

// 把cat改成dog,这可行吗?
memcpy(reinterpret_cast<char*>(cat), reinterpret_cast<char*>(dog), sizeof(Dog));

我推测这属于未定义行为,但并非完全确定。

背景:我正在编写一个类型检查器,需要随着获取到更多信息来重写类型。我考虑过将Type类重构为联合类型,但这需要大量工作,也欢迎其他可行方案。

内容的提问来源于stack exchange,提问作者samvv

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 12:29:59