Search code examples
c++boostboost-interprocess

Getting pointers to managed_shared_memory of boost interprocess


In all examples of boost interprocess, I only see it being initialized in main().

#include <boost/interprocess/managed_shared_memory.hpp>
#include <iostream>

using namespace boost::interprocess;

int main()
{
  shared_memory_object::remove("Boost");
  managed_shared_memory managed_shm(open_or_create, "Boost", 1024);
  int *i = managed_shm.construct<int>("Integer")(99);
  std::cout << *i << '\n';
  std::pair<int*, std::size_t> p = managed_shm.find<int>("Integer");
  if (p.first)
    std::cout << *p.first << '\n';
}

Rather than specifically a boost question, this is more of a C++ question where I know i can create an object and initialize managed_shm using the initialization list, but I want to know if there is a way to declare it like managed_shared_memory * managed_shm; and later initialize it like managed_shm = new managed_shm(open_or_create, "Boost", 1024);?

I have seen the managed_shared_memory header, and they didn't seem to provide any option to do so.


Solution

  • Yeah sure. Just write it like that.

    #include <boost/interprocess/managed_shared_memory.hpp>
    #include <iostream>
    
    namespace bip = boost::interprocess;
    
    struct MyWorker : boost::noncopyable {
        MyWorker() 
            : _shm(new bip::managed_shared_memory(bip::open_or_create, "089f8a0f-956a-441d-9b9e-e0696c43185f", 10ul<<20)) 
        {}
    
        ~MyWorker() {
            delete _shm;
        }
      private:
        bip::managed_shared_memory* _shm;
    };
    
    int main() {
        MyWorker instance;
    }
    

    Live On Coliru using managed_mapped_file instead of shared memory (which isn't supported on Coliru)

    Of course, prefer smart pointers.

    Or indeed, ask yourself why you need dynamic allocation (I cannot think of a valid reason for this)

    I you use some kind of API that (mistakenly!) requires a pointer, just take the address:

    bip::managed_shared_memory shm(bip::open_or_create, "SHM_NAME", 10ul<<20);
    
    // calling a badly design API takes a pointer:
    misguided_api_foo(&shm);