Search code examples
c++boostg++shared-memoryboost-interprocess

Error when trying to compile app using boost::interprocess::managed_shared_memory::construct<T>


I'm receiving a strange compilation error when trying to use construct<T>() method of a boost::interprocess::managed_shared_memory class. I'm using the Boost library in 1.48 version and GCC in 4.6.3 version.

The problem is that when I'm creating a managed_shared_memory object (which is not a member of the struct) and then I'm trying to construct any object by using it's construct<T>() method, the compilation succeeds:

#include <boost/interprocess/managed_shared_memory.hpp>
namespace proc = boost::interprocess;

template <typename _T>
void TFunc() {
    proc::managed_shared_memory mem;
    mem = proc::managed_shared_memory(proc::create_only, "mem1", 1024);
    int* ob1 = mem.construct<int>("i1") ();
}

Although, when the managed_shared_memory object is defined inside a struct and then created, the compilation of usage of construct<T>() method fails :

#include <boost/interprocess/managed_shared_memory.hpp>
namespace proc = boost::interprocess;

template <typename _T>
void TFunc() { 
    struct MemoryHandler {
        proc::managed_shared_memory mem;
    } handler;

    handler.mem = proc::managed_shared_memory(proc::create_only, "mem2", 1024);
    int* ob2 = handler.mem.construct<int>("i2") ();  // failure
}

with the following GCC error, pointing at the line with construct usage method:

error: expected primary-expression before 'int'
error: expected ',' or ';' before 'int'

Unfortunately I have not tested it against another versions of Boost and GCC, so I don't know if it's a bug of Boost/GCC or a feature.

Has anyone struggled with similar error or know what can be the cause?


Solution

  • You haven't shown a complete example that demonstrates the error, so I can only guess, but I suspect the line that fails is inside a template and handler is a dependent type.

    To fix it you need to tell the compiler that construct is a function template:

    int* ob2 = handler.mem.template construct<int>("i2") ();
                           ^^^^^^^^
    

    See the C++ Templates FAQ for more information.

    And next time please post a complete example so others can reproduce the exact problem, instead of making people guess. For example, here is a minimal, complete example that shows the same error:

    #include <boost/interprocess/managed_shared_memory.hpp>
    
    namespace proc = boost::interprocess;
    
    struct MemoryHandler{
            proc::managed_shared_memory mem;
    } handler;
    
    template<typename T> void f(T handler)
    {
      handler.mem = proc::managed_shared_memory(proc::create_only, "mem2", 10);
      int* ob2 = handler.mem.construct<int>("i2") ();  // failure
    }