class C
{
public:
C(int k) : arrSize(k)
{
arr = new int[k];
}
C(const C&); // you need to add this (Lookup: Rule of 3)
C& operator=(const C&); // you need to add this (Lookup: Rule of 3)
~C() // this is 1 of the Rule of 3, so you need all 3
{
delete arr; // this needed to be: delete [] arr;
} // since you did a new [] in the constructor
private:
int arrSize;
int *arr;
};
class B
{
public:
C& getC()
{
C c(8); // * see Note
return c;
}
};
- Note that getC() returns a pointer to the stack, when another function uses that stack space the contents of
c
will get overwritten (corrupt)
There is a difference between a memory leak and memory growth - not using delete []
can cause a leak. A leak is when there are no references to allocated memory. Memory growth is often called a leak, but occurs when memory has references but will not be used, for example an allocator that keepss a list of freed memory, but never makes it available for reuse. Since the list exists, it is not a leak, it is memory growth.