0

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
mike
  • 167
  • 2
  • 6
  • i'm stuck in the stone ages here and can only use gcc 4.4.7 which does not have the c++11 spec and thus no `std::make_unique` so no smart pointers – mike Aug 09 '17 at 20:59
  • You can (and should) edit your question instead of adding vital information in comments. – sehe Aug 09 '17 at 21:07

1 Answers1

2

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
sehe
  • 374,641
  • 47
  • 450
  • 633
  • thanks @sehe for the response. i should have noted in the description that i'm stuck in the stone ages here and can only use gcc 4.4.7 which does not have the c++11 spec and thus no `std::make_unique` – mike Aug 09 '17 at 20:58
  • So, replace `std::make_unique(n)` with `Ptr(new MyObject(n))`. Or write your own 3-line `make_unique`:) – sehe Aug 09 '17 at 20:59
  • Completely c++11-proofed version: http://coliru.stacked-crooked.com/a/5029747707aa4cca – sehe Aug 09 '17 at 21:01
  • In case you can't have unique_ptr: [completely c++03-proofed](http://coliru.stacked-crooked.com/a/797c3c11d05cb15f) – sehe Aug 09 '17 at 21:06
  • 1
    thank you @sehe that last link works like i want it to! – mike Aug 09 '17 at 21:15