Dynamic memory

Can someone tell me if I'm thinking in right direction?
We use dynamic memory to use data that would normaly be destroyed.

For example:
1
2
3
4
5
6
7
 string *pString;
	{
		string pString1("HiMom");
		pString = &pString1;
	}
        //displays nothing
	cout << *pString << endl;

1
2
3
4
5
6
7
shared_ptr<string> pString;
	{
		shared_ptr<string> pString1 = make_shared<string>("HiMom");
		pString = pString1;
	}
        //displays HiMom
	cout << *pString << endl;
1
2
        //displays nothing
	cout << *pString << endl;


That does not necessarily display nothing. It might crash the program because you are accessing invalid memory. You should never, ever do that.


Can someone tell me if I'm thinking in right direction?
We use dynamic memory to use data that would normaly be destroyed.


Not really, no.

You use dynamic memory mostly for when the number or type of objects you need are not known at compile time. Like... if the size of an array isn't known until the user inputs a number, or you get some information from a file or something.
Well I know that I musn't use first code ever because it could crash program, it was just an example.

Book C++ Primer says when to use dynamic memory;
1. They don't know how many objects they'll need
2. They don't know the precise tyep of the objects they need
3. They want to share datt between several objects

I thought of dynamic memory to be hard topic I wasn't really sure that I would understand it.

Thanks for your answer!
Last edited on
Topic archived. No new replies allowed.