Can I force std::vector to not deallocate its memory after the vector goes out of scope?
For example, if I have
This is a bad idea, but possible by creating a custom allocator that does not deallocate as said in other answers.
For example : (boilerplate mostly from cppref)
#include
#include
#include
template
struct LeakingAllocator
{
using value_type = T;
LeakingAllocator() = default;
template constexpr LeakingAllocator(const LeakingAllocator&) noexcept {}
T* allocate(std::size_t n)
{
if(n > std::size_t(-1) / sizeof(T)) throw std::bad_alloc(); // check for overflow
if(auto p = static_cast(std::malloc(n*sizeof(T)))) return p; // return p if malloc returns a valid object
throw std::bad_alloc(); // otherwise just throw.
}
void deallocate(T* p, std::size_t) noexcept { /*leak intentionally*/ }
};
template
bool operator==(const LeakingAllocator&, const LeakingAllocator&) { return true; }
template
bool operator!=(const LeakingAllocator&, const LeakingAllocator&) { return false; }
template
using LeakingVector = std::vector>;
Then code like
int* ret()
{
LeakingVector a;
a.resize(10);
return &a[0];
}
int main()
{
auto ptr = ret();
*ptr = 10;
std::cout << *ptr;
}
becomes valid.