Alright so Say I have a class with all its definition, bla bla bla…
template <class DT>
class Foo{
private:
DT* _data;
//other stuff;
public:
Foo(DT* data){ _data = data; }
virtual ~Foo(){ delete _data; }
//other methods
};
And then I have in the main method:
int main(){
int number = 12;
Foo<anyRandomClass>* noPrimitiveDataObject = new Foo<anyRandomClass>(new anyRandomClass());
Foo<int>* intObject = new Foo<int>(number);
delete noPrimitiveDataObject; //Everything goes just fine.
delete intObject; //It messes up here, I think because primitive data types such as int are allocated in a different way.
return 0;
}
My question is: What could I do to have both delete statements in the main method work just fine?
P.S.: Although I have not actually compiled/tested this specific code, I have reviewed it extensively (as well as indented), so if you find a mistake, please be nice.
You’re taking the address of a literal and then calling
deleteon it later, which is wrong. It was not allocated withnew, therefore you cannot deallocate it withdelete(nor would it make any sense to).If you had written
new int(12)instead it would be ok, however, there are other problems.First, your class violates The Rule of Three. What happens if I copy
intObjectand then calldeleteon both of them? You end up callingdeleteon the same pointer twice.Second, why are you allocating these things dynamically to begin with? You create an RAII style wrapper to handle deallocation for you… and then proceed to allocate it manually. What problem is that solving?
I suppose this is an exercise for you, and that’s great. Just remember what problem you’re trying to solve with this code.
If I am using a
std::vector<T>I am certainly not going to use it like this:It defeats the entire purpose of using a vector! Now I have to manually manage this pointer/memory, and that’s the problem that the vector class (and other RAII style classes) were created to solve.
So, to use it properly, you do this:
Use automatic storage duration to your advantage, that’s the whole point. Also be very clear about who owns the memory. If it is not clear from your class design who owns a given chunk of memory then it is not safe to
deleteit in your destructor.Ok, you changed the code to this now:
Same problem; you are taking the address of a variable allocated with automatic storage duration and then calling
deleteon it. This is wrong. Anything you allocate withnewyou deallocate withdelete, but nothing else. Ever. That’s it.