Search code examples
c++boostshared-ptrsmart-pointers

Converting pointers to boost::shared_ptr


I have the following code:

#include <boost\interprocess\file_mapping.hpp>

file_mapping* fm = new file_mapping(FilePath,read_only);

How can I convert this line to use boost::shared_ptr?

Whenever I attempt shared_ptr<file_mapping> I then get compile errors on the right hand side with the new operator.


Solution

  • The constructor of shared_ptr<T> is explicit: you don't want to have a shared_ptr<T> accidentally taking ownership of your T* and delete it when done. Thus, you need to explicitly construct a shared_ptr<T> from the pointer, e.g.,

    boost::shared_ptr<file_mapping> ptr(new file_mapping(FilePath, read_only));
    

    ... or even something like

    std::shared_ptr<file_mapping> ptr = std::make_shared<file_mapping>(FilePath, read_only);