Garbage Collector in C++..

Hello guys,
I wanna ask a question related with memory management.
I many times allocate memory (for ex. int a = new int) but don't delete them in a C++ Class.
So how to control it?
In simple procedure programs, I know to make a free of the memory (by delete function), however, I am not able to use it in Classes.

Are there any suggestions?
Thanks in advance!
Use the destructor:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

class MyClass
{
    char* buffer;
public:
    MyClass()
    {
        std::cout << "Constructor: allocate your objects here\n";
        buffer = new char[1024]; // allocate
    }

    ~MyClass()
    {
        std::cout << "Destructor: delete your objects here\n";
        delete[] buffer; // delete
    }
};
Last edited on
You can use smart pointers to be sure that you avoid errors
( in a class like the above, you should write a copy constructor and operator as well )
yeah, thank you very much guys. I did as you showed. And still i feel lack of skill on programming languages.
So, what about a condition below:

struct sA{
int x;
}


Class A{
public:
void funcA(vector<sA*>);
int *k;
};


A::A(){}
A::~A(){ delete k; }

void A::funcA(vector<sA*> vA){
sA* ssA = new sA;
for (k=0; k<10; k++)
{
ssA->x = k;
vA.push_back(ssA);
}
// here I deleted ssA but it gave me heap error
}


where should I delete ssA?
please help!
Thanks in advance.
Last edited on
Are all the functions declared correctly inside the class? Cause I see that your constructor and destructor are not declared according to your code


1
2
3
4
5
6
7
8
9
10
11
12
13
14
struct sA
{
     int x;
}

class A
{
public:
      int *k;
     A();
    ~A(){ delete k; };
     void funcA(vector<sA*>);
    
};


Try this for now and rebuild to see if that fixes your heap error after you put in the delete command.
Last edited on
Topic archived. No new replies allowed.