这个问题与 SO 中具有相似名称的问题不重复
It is well-known that if DLLs are statically linked (/MT flag in MSVC), the DLL that has allocated the memory MUST deallocate it; otherwise memory deallocation will cause runtime errors.
问题是:
- 我在 DLL 中分配了一个
std::vector
,比如A
。 A
将 vector 传递给 DLL,比如B
。- DLL
B
向 vector 中插入数据。 - 现在,如果 DLL
A
试图破坏 vector ,它将面临错误。
我发现,如果我在将 vector 传递给 B
之前使用 std::vector::reserve
,则可以使 vector 足够大以容纳数据,并且防止内存重新分配 - 这通常发生在项目插入期间 - 然后在尝试破坏 vector 时我不会在 A
中收到错误。看起来,在内存重新分配的情况下,B
在其自己的堆中分配 vector 。我的推理是错误的吗?我怎样才能避免这种情况?
最佳答案
最简单的方法是将 vector
隐藏在从 dll 公开的方法中,这样您就可以获得一个 const vector
以在其他 dll 中查看,但不能修改它.然后在 dll B 中创建一个新函数,代表调用者将条目添加到 vector 中。
因此您的vector
仍然隐藏在 dll B 中以进行所有修改。
关于c++ - 跨 DLL 边界 vector 的内存重定位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39263448/