Dynamic Memory(Smart Pointers)

So I just finished my chapter in C++ primer about dynamic memory. It talks about smart pointers such as shared or unique pointers and they are automatically destroyed if the pointer is not called anymore, in addition to that it discussed about the old route of dynamic memory using new and delete but the book heavily disadvised using those. So I have a couple questions:

1.)Should a programmer always use smart pointers?
2.)When you use dynamic memory, does it use the heap or the stack memory?
3.)Should you only use pointers when you have large objects that take a lot of space?(For example you build a class that has a lot of variables and functions).
4.)When you instantiate an object without a pointer, are you wasting precious memory, should you use pointer for everything?(Example
1
2
string name = "Jacob";//This is not a pointer, name is a string with a value of Jacob
shared_ptr<string> name = make_shared<string>("Jacob");//Now we got a pointer, the memory can be freed! 
).
Last edited on

Here is my 2p

1.)Should a programmer always use smart pointers?


Not always. Think abut the people who wrote the smart pointers. Sometimes dealing with raw pointers is inevitable.

2.)When you use dynamic memory, does it use the heap or the stack memory?


It uses the "free store". How the "free store" is implemented is up to the compiler. Usually it is a heap.

3.)Should you only use pointers when you have large objects that take a lot of space?


No. Use pointers when it is semantically appropriate.

4.)When you instantiate an object without a pointer, are you wasting precious memory, should you use pointer for everything?


No. When you instantiate an object without a pointer it is called an "automatic" variable because its memory will be freed automatically when it goes out of scope. You should use pointers only when necessary.
Thanks Galik!
Topic archived. No new replies allowed.