【发布时间】:2021-03-20 17:12:38
【问题描述】:
我正在开发一个内存容量有限的 Arduino 项目,所以许多 C++ 神奇的便利都在窗外,其中之一就是能够在任何你想要的地方分配内存(如果你这样做可能会导致 Heap Fragmentation) .但是OOP需要指针和分配:
class StateBase
{
virtual run();
};
class StateA : public StateBase
{
int bigArr[100];
virtual run();
};
//About 5 more States, with different member variables
//Usually in Arduino, you allocate a big chunk of heap memory, and keep reusing it:
StateBase *memPool[] = {new StateA(), new StateB(), new...};
但我想试试这个,令我惊讶的是,它有效:
StateBase *memPool = new StateBase();
//...do something, now I need to switch state
StateA newState;
memcpy(memPool, &newState, sizeof(StateA));
问题:
- 这是个坏主意吗?有什么后果吗?
- 您应该使用
memPool = new (memPool) StateA()代替 memcpy 吗? - 为什么它会起作用,显然 StateBase 和 StateA 的大小不同?
【问题讨论】:
-
由于 StateA 比 StateBase 大得多,因此您将在分配的内存之后写入。它是允许的,但它不是工作,因为您可能会覆盖其他数据。最终,在访问该数据时,您会遇到问题。