提升circular_buffer持有指针

时间:2017-08-09 20:01:11

标签: boost circular-buffer

有没有办法可以确保我的对象在循环缓冲区被覆盖之前被删除?这里有一些代码来说明我的问题。

boost::circular_buffer<MyObject*> cBuf(5);
cBuf.push_back(new MyObject()); // cBuf[0]
cBuf.push_back(new MyObject()); // cBuf[1]
cBuf.push_back(new MyObject()); // cBuf[2]
cBuf.push_back(new MyObject()); // cBuf[3]
cBuf.push_back(new MyObject()); // cBuf[4]

// before this overwrite occurs, how do i make sure the pointer
// position cBuf[0] is deleted?
cBuf.push_back(new MyObject()); // this will overwrite position 0

1 个答案:

答案 0 :(得分:0)

这是智能指针的经典场景。任何智能指针。

最简单的选择是std :: unique_ptr:

<强> Live On Coliru

#include <boost/circular_buffer.hpp>
#include <iostream>

struct MyObject {
    MyObject(int i) : _i(i) { std::cout << __FUNCTION__ << " _i=" << _i << "\n"; }
   ~MyObject()              { std::cout << __FUNCTION__ << " _i=" << _i << "\n"; }
   int _i;
};

int main() {
    using Ptr = std::unique_ptr<MyObject>;
    boost::circular_buffer<Ptr> cBuf(5);
    cBuf.push_back(std::make_unique<MyObject>(0)); // cBuf[0]
    cBuf.push_back(std::make_unique<MyObject>(1)); // cBuf[1]
    cBuf.push_back(std::make_unique<MyObject>(2)); // cBuf[2]
    cBuf.push_back(std::make_unique<MyObject>(3)); // cBuf[3]
    cBuf.push_back(std::make_unique<MyObject>(4)); // cBuf[4]

    std::cout << "Full, pushing extra\n";

    cBuf.push_back(std::make_unique<MyObject>(5)); // this will overwrite position 0

    std::cout << "Done\n";
}

打印:

MyObject::MyObject _i=0
MyObject::MyObject _i=1
MyObject::MyObject _i=2
MyObject::MyObject _i=3
MyObject::MyObject _i=4
Full, pushing extra
MyObject::MyObject _i=5
MyObject::~MyObject _i=0
Done
MyObject::~MyObject _i=1
MyObject::~MyObject _i=2
MyObject::~MyObject _i=3
MyObject::~MyObject _i=4
MyObject::~MyObject _i=5