Advertisement

I think I don't understand dynamic memory

Started by February 28, 2015 04:06 PM
14 comments, last by Pink Horror 9 years, 10 months ago

hello people,

Currently i'm learning C++. My book explains Dynamic Memory a bit like this:

-You have to now the "value" of a static array when you write the program. But with a dynamic array you can do this in run time.

Dynamic Memory is basically a pointer in a class. This pointer will be pointing to a block of memory (array). You have to write a destructor for this, like this:


class IntArray{
private:
      int amountOfValuesInArray;
      int *p;
public:
     IntArray(amount)
           :amountOfValuesInArray(amount){
                 p = new int [amountOfValuesInArray]
           }

ETC. 

But then I get to smart pointers: Smart pointers don't need a destructor, but will "free" the memory by themselves, and then I get the following example (I copied it and it isn't in english, I hope it's understandable, otherwise I will translate it(tell me it)):


class Student {
private:
  string naam, opleiding, geslacht;
  int nummer;

public:
  Student( string n, string opl, string gesl, int nr )
    : naam(n), opleiding(opl), geslacht(gesl), nummer(nr) {
  }

 string toString() const {
    ostringstream os;
    os << naam << ", " << opleiding << ", " << geslacht;
    os << ", " << nummer << endl;
    return os.str();
  }
};

int main() {
  //shared_ptr<Student> sp( new Student( "Gertjan", "wiskunde", "m", 313 ) );
  auto sp = make_shared<Student>( "Gertjan", "wiskunde", "m", 313 );
  cout << sp -> toString() << endl;
  cin.get();

}

And the book says that at the end nothing is pointing towards the memory of sp anymore, so the memory will be "released".

But in this class there isn't any dynamic memory (array/pointer) right, so I think I don't understand it. Could you tell me what I understand wrong and how it works then?

Thanks

Dynamic memory means that the memory lifetime isn't managed automatically by the language - like how when you call a function, memory is automatically provided for the various local variables you need.

Dynamic memory is, by default, managed explicitly by the programmer. This is the familiar new / delete or new[] / delete[] calls.

However, by using the other features of the language, namely destructors, this can be automated again - the explicit memory management is done by the implicitly called destructors. So the std::make_shared<> will dynamically allocate the object, and the destructor deallocates it.

Now, to come to your Student class. It may in fact use dynamic memory, as std::string is dynamically sized (though some implementations can avoid allocations for short strings). However, this is irrelevant, as any object can be dynamically allocated - you can dynamically allocate an "int" if you want.
Advertisement

http://en.cppreference.com/w/cpp/memory/shared_ptr/make_shared is the dynamic allocation. It's doing so then it's taking that an putting it into sp.

The "auto" keyword makes sp the same type as what's being given to it (the right side of the =).

That's where the dynamic allocation is happening.

Oh, then I don't understand Dynamic Memory, could someone please explain it to me, or point me to an article or something like that, because I dind't understand Rip-Off's explaination completely.


I dind't understand Rip-Off's explaination completely.


the explicit memory management is done by the implicitly called destructors. So the std::make_shared<> will dynamically allocate the object, and the destructor deallocates it.

When any object goes out of scope, its destructor is called. When the main function is exited, sp goes out of scope, so its destructor is called. That shared_ptr destructor ends up deallocating the memory it allocated when it was constructed. Just like your IntArray class allocated in its constructor, and deallocated in the destructor (I'm assuming so, you didn't post your destructor code).

So if you had the code:


int main() {
    IntArray blah(10);
    // etc... do some more stuff
}

When the main function exits, IntArray goes out of scope and its destructor will be called, thus freeing the *p it allocated in its constructor.


I dind't understand Rip-Off's explaination completely.


the explicit memory management is done by the implicitly called destructors. So the std::make_shared<> will dynamically allocate the object, and the destructor deallocates it.

When any object goes out of scope, its destructor is called. When the main function is exited, sp goes out of scope, so its destructor is called. That shared_ptr destructor ends up deallocating the memory it allocated when it was constructed. Just like your IntArray class allocated in its constructor, and deallocated in the destructor (I'm assuming so, you didn't post your destructor code).

So if you had the code:


int main() {
    IntArray blah(10);
    // etc... do some more stuff
}

When the main function exits, IntArray goes out of scope and its destructor will be called, thus freeing the *p it allocated in its constructor.

I understand that, but I meant just the whole thing Dynamic Memory in general. (The theory behind it)

Advertisement

Lets say you were making a program to store students quiz grades for the semester.

You chose to store it in a dynamic array of ints.
Now being in different classes the students aren't going to have the exact same number of quiz scores.

so when you got to the point where you needed to type in the variable, without a dynamically allocated array it would be like:

int studentGrade[5];

You would have to hardcore that number in there. Which in this case you would be making an assumption as to how many quiz's he has taken. What if he took more than 5? What if he took less? Making a dynamically allocated array you can put a variable in those brackets so that way the user can specify at run time how many he's going to enter. So you could use a variable like this instead as opposed to that hardcoded number/#defines and whatnot.

studentGrade[numOfGrades]

So prior you can prompt the user asking them how many grades will they be entering, or however you want to implement that part.

If I misunderstood what you were asking for sorry.

Lets say you were making a program to store students quiz grades for the semester.

You chose to store it in a dynamic array of ints.
Now being in different classes the students aren't going to have the exact same number of quiz scores.

so when you got to the point where you needed to type in the variable, without a dynamically allocated array it would be like:

int studentGrade[5];

You would have to hardcore that number in there. Which in this case you would be making an assumption as to how many quiz's he has taken. What if he took more than 5? What if he took less? Making a dynamically allocated array you can put a variable in those brackets so that way the user can specify at run time how many he's going to enter. So you could use a variable like this instead as opposed to that hardcoded number/#defines and whatnot.

studentGrade[numOfGrades];

So prior you can prompt the user asking them how many grades will they be entering, or however you want to implement that part.

If I misunderstood what you were asking for sorry.

Really thanks for your effort, but I understood that already.

I Understand the array part, but in my example, there is no array, so I don't understand it properly there.

Thanks again!!!!!

Lets say you were making a program to store students quiz grades for the semester.

You chose to store it in a dynamic array of ints.
Now being in different classes the students aren't going to have the exact same number of quiz scores.

so when you got to the point where you needed to type in the variable, without a dynamically allocated array it would be like:

int studentGrade[5];

You would have to hardcore that number in there. Which in this case you would be making an assumption as to how many quiz's he has taken. What if he took more than 5? What if he took less? Making a dynamically allocated array you can put a variable in those brackets so that way the user can specify at run time how many he's going to enter. So you could use a variable like this instead as opposed to that hardcoded number/#defines and whatnot.

studentGrade[numOfGrades];

So prior you can prompt the user asking them how many grades will they be entering, or however you want to implement that part.

If I misunderstood what you were asking for sorry.

Really thanks for your effort, but I understood that already.

I Understand the array part, but in my example, there is no array, so I don't understand it properly there.

Thanks again!!!!!

To my knowledge it didn't make an array in the second one. It dynamically created an instance of student.

That line with the make_shared ( like I said I haven't used smart pointers, but this is an assumption ), that line is the equivalent of doing it manually say:

_student = new Student("whatever arguments they used");

and if you wanted to delete it manually you would've done:

delete _student;

_student = nullptr;

but since it was a smart pointer you didn't have to worry about doing the above.

Lets say you were making a program to store students quiz grades for the semester.

You chose to store it in a dynamic array of ints.
Now being in different classes the students aren't going to have the exact same number of quiz scores.

so when you got to the point where you needed to type in the variable, without a dynamically allocated array it would be like:

int studentGrade[5];

You would have to hardcore that number in there. Which in this case you would be making an assumption as to how many quiz's he has taken. What if he took more than 5? What if he took less? Making a dynamically allocated array you can put a variable in those brackets so that way the user can specify at run time how many he's going to enter. So you could use a variable like this instead as opposed to that hardcoded number/#defines and whatnot.

studentGrade[numOfGrades];

So prior you can prompt the user asking them how many grades will they be entering, or however you want to implement that part.

If I misunderstood what you were asking for sorry.

Really thanks for your effort, but I understood that already.

I Understand the array part, but in my example, there is no array, so I don't understand it properly there.

Thanks again!!!!!

To my knowledge it didn't make an array in the second one. It dynamically created an instance of student.

That line with the make_shared ( like I said I haven't used smart pointers, but this is an assumption ), that line is the equivalent of doing it manually say:

_student = new Student("whatever arguments they used");

and if you wanted to delete it manually you would've done:

delete _student;

_student = nullptr;

but since it was a smart pointer you didn't have to worry about doing the above.

yes, but I don't understand exactly what's Dynamic about the _student = new Student("whatever arguments they used"); part

This topic is closed to new replies.

Advertisement