gpt4 book ai didi

c++ - 在不破坏的情况下 boost::interprocess 共享内存删除对象

转载 作者:行者123 更新时间:2023-11-30 03:31:58 24 4
gpt4 key购买 nike

我在 Windows 上有一个 boost interprocess managed_shared_memory 并且我有一个 boost interprocess vector 存储在其中。 vector 由

创建或打开
auto* vec = shm.find_or_construct< MyVector >( "Data" )( shmAllocator );

如 boost 进程间示例中所述。我的观点是,我现在构造或打开了一个对象 vec引用共享内存中的对象。我检查了 vec 的 d'tor 仅在我使用 shm.destroy<MyVector>("Data") 时被调用如果我调用delete vec应用程序崩溃。

现在如何在不破坏底层数据的情况下正确释放对象“vec”?完整的场景:

  • 两个用户正在运行我的软件,通过共享内存共享数据(在使用文件模拟的窗口中)
  • 一个用户退出软件,如果我不调用destroy我有内存泄漏,如果我确实按照 boost 文档中的说明调用它:

In Windows operating systems, current version supports an usually acceptable emulation of the UNIX unlink behaviour: the file is renamed with a random name and marked as to be deleted when the last open handle is closed

  • 另一个用户启动该软件并尝试共享内存,但由于文件已重命名,它无法与我的软件的其他运行实例共享内存。

最佳答案

The vector is created or opened by

这有点混淆了概念。它被查找,并在必要时构建。 (open_or_create 适用于实际的可共享对象,如内存映射或共享内存对象)。

I checked that the d'tor of vec is only called when i use shm.destroy<MyVector>("Data") and if i call delete vec the application crashes.

这都是设计使然。

One user exits the software and if i do not call destroy i have a memory leak,

不是真的。如果不销毁 vector ,它仍然存在于托管段中。这意味着您可以重新打开共享内存段并仍然在那里找到它。

要删除共享段,请使用 remove()

docs说这与此相关:

When the managed_mapped_file object is destroyed, the file is automatically unmapped, and all the resources are freed. To remove the file from the filesystem you could use standard C std::remove or Boost.Filesystem's remove() functions, but file removing might fail if any process still has the file mapped in memory or the file is open by any process.

To obtain a more portable behaviour, use file_mapping::remove(const char *) operation, which will remove the file even if it's being mapped. However, removal will fail in some OS systems if the file (eg. by C++ file streams) and no delete share permission was granted to the file. But in most common cases file_mapping::remove is portable enough.

here :

  1. ~basic_managed_mapped_file();

Destroys *this and indicates that the calling process is finished using the resource. The destructor function will deallocate any system resources allocated by the system for use by this process for this resource. The resource can still be opened again calling the open constructor overload. To erase the resource from the system use remove()

附加信息

如果你真的只是希望在最后一个用户释放它之后 vector 消失,使用进程间共享指针:http://www.boost.org/doc/libs/1_64_0/doc/html/interprocess/interprocess_smart_ptr.html#interprocess.interprocess_smart_ptr.shared_ptr

关于c++ - 在不破坏的情况下 boost::interprocess 共享内存删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43802330/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com