mike
mike

Reputation: 167

boost circular_buffer holding pointers

is there a way i can ensure my object gets deleted before it is overwritten in a the circular buffer? here is some code to illustrate my question.

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

Upvotes: 0

Views: 1024

Answers (1)

sehe
sehe

Reputation: 392883

This is the classical scenario for smart pointers. Any smart pointer.

The simplest choice would be 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";
}

Prints:

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

Upvotes: 2

Related Questions