I've got a background in C and am trying to get my head around C++ classes and how the destructors get called as objects leave scope. As a side note, given the nature of what I am trying to do, I would rather not use STL structures like std::array<> or std::vector<> for the data containers I present below.
Here's a high level overview of my understanding. Given some class:
class some_class{
public:
int * member;
size_t n_members;
some_class(size_t count) ...
~some_class() ...
// a member function or operator overload
// that returns an instance of some_class
some_class do_something()
}
...
some_class * container;
// Some scope
{
some_class foo = some_class();
some_class * bar = new some_class();
container[0] = bar;
}
When some_class foo
leaves the scope, its destructor gets called. If I wanted to store a pointer to an instance of some_class
into container
outside of the scope, I need to instantiate some_class bar
on the heap so that memory does not immediately get de-allocated upon leaving scope - just like I would in C.
Now, the purpose of some_class
is to hold an arbitrarily large amount of data and so int * member
needs to be allocated on the heap.
Given above, the constructor and destructor for some_class() will look something like this:
// some_class constructor
some_class::some_class(size_t count) : n_members(count){
member = new int[count];
}
// some_class destructor
some_class::~some_class(){
delete[] member;
}
Now my problem becomes apparent: If I need to add an instance of some_class
returned from the do_something()
method, I am guaranteed to have a memory error (in this case, a double-free) because do_something()
returns a stack-allocated some_class
:
some_class * container = new some_class[n];
// Some scope
{
some_class foo = some_class();
some_class bar = foo.do_something();
container[0] = &bar; // <-- I know this is stupid but that's the point of this question
}
delete[] container;
My way around this is to make foo.do_something()
return a pointer to an instance of some_class
. Of course, not a solution. How would one properly address such a situation in true C++ way?
For example, one thing I've been reading up on was the use of shared pointers or unique pointers (or smart pointers in general). However, my understanding is that using these pointers requires you to have instantiated your object in the heap. It also really doesn't help the whole issue about requiring foo.do_something()
to return a pointer.
Anyways, any thoughts would be appreciated.