I'm trying to do a simple buffer and follow the RAII idiom
in main.cpp
int main()
{
buffer buf(5);
buffer test(10);
test = buf;
return 0;
}
in buffer.cpp
#include "buffer.h"
#include <iostream>
size_t buffer::get_size() const
{
return length;
}
buffer::buffer(size_t length) : start(new int[length]), length(length)
{
std::cout << length << +" size" << std::endl;
}
buffer::buffer(const buffer& rhs) : start(new int[rhs.get_size()]), length(rhs.get_size())
{
std::copy(rhs.begin(), rhs.end(), start);
}
buffer& buffer::operator=(const buffer& rhs)
{
buffer temp = rhs;
std::swap(*this, temp);
return *this;
}
int* buffer::begin()
{
return start;
}
int* buffer::end()
{
return start + length;
}
const int* buffer::begin() const
{
return start;
}
const int* buffer::end() const
{
return start + length;
}
buffer::buffer(buffer&& rhs) noexcept
{
*this = std::move(rhs);
}
buffer& buffer::operator=(buffer&& rhs) noexcept
{
if (this != &rhs) { // if this is not the rhs object
start = rhs.start;
length = rhs.length;
rhs.start = nullptr;
rhs.length = 0;
}
return *this;
}
buffer::~buffer()
{
delete[] start;
}
in buffer.h
#pragma once
class buffer {
size_t length;
int* start;
public:
size_t get_size() const;
explicit buffer(size_t size);
buffer(const buffer& rhs);
buffer& operator=(const buffer& rhs);
buffer& operator=(buffer&& rhs) noexcept;
buffer(buffer&& rhs) noexcept;
int* begin();
int* end();
const int* begin() const;
const int* end() const;
~buffer();
};
Now as you notice in main buf is a smaller size than test. My question is what happens to the memory allocated by test on the line above test=buf?
Does it ever get cleaned up? Or do main have to finish before it gets cleaned up.