在boost managed_memory_segment中使用私有构造函数构造对象

时间:2018-03-14 16:11:54

标签: c++ boost

我有一个如下课程:

class X {
public:
    static X *factory(...);
    static void destroy(X *x);

private:
    X();
    ~X();

};

我正在尝试使用boost managed_shared_memory在

中的示例中在共享内存中构造此对象

http://www.boost.org/doc/libs/1_47_0/doc/html/interprocess/managed_memory_segments.html#interprocess.managed_memory_segments.managed_memory_segment_features.allocation_types

在这种情况下,如果构造函数是私有的,我如何使用find_or_construct()或construct()?我们是否强制使构造函数公开,而不是对共享内存中构造的类使用factory / destroy方法?

谢谢, S.K

1 个答案:

答案 0 :(得分:0)

您可以简单地将引用传递给段管理器(或相关的分配器,具体取决于您的要求)。

对于任何使用它们的嵌入式对象,通常都会要求分配器。

<强> Live On Coliru

#include <boost/interprocess/allocators/allocator.hpp>

namespace bip = boost::interprocess;

class X {
public:
    template <typename SegmentManager>
    static X* factory(int id, SegmentManager* sm) {
        bip::allocator<X, SegmentManager> alloc{sm};
        X* x = alloc.allocate(1).get();
        new (x) X(id);
        return x;
    }
    template <typename SegmentManager>
    static void destroy(X *x, SegmentManager* sm) {
        if (!x) return;

        bip::allocator<X, SegmentManager> alloc{sm};
        x->~X();
        alloc.deallocate(x, 1);
    }

    int getId() const { return id; }

private:
    X(int id) : id(id) {}
    ~X() = default;

    int id;
};

#include <iostream>

template <typename Segment>
void run_test(Segment& segment) {
    std::cout << "Free: " << segment.get_free_memory() << '\n';

    auto sm = segment.get_segment_manager();

    auto a = X::factory(42, sm);
    auto b = X::factory(43, sm);
    std::cout << "Free: " << segment.get_free_memory() << '\n';

    X& aref = *a;

    std::cout << "a.id = " << aref.getId() << "\n";
    std::cout << "b.id = " << b->getId() << "\n";

    X::destroy(a, sm);
    X::destroy(b, sm);
    std::cout << "Free: " << segment.get_free_memory() << '\n';
}

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

int main() {
    bip::managed_mapped_file mmf(bip::open_or_create, "test.bin",       10240);
    bip::managed_shared_memory msm(bip::open_or_create, "MySharedMemory", 10240);

    std::cout << " ------------- managed_mapped_file ---------------\n";
    run_test(mmf);
    std::cout << " ------------- managed_shared_memory -------------\n";
    run_test(msm);
}

打印:

 ------------- managed_mapped_file ---------------
Free: 10016
Free: 9920
a.id = 42
b.id = 43
Free: 10016
 ------------- managed_shared_memory -------------
Free: 10016
Free: 9920
a.id = 42
b.id = 43
Free: 10016