0
Is it true that we need to manage memory by ourselves?
I heard c++ is different from c# and one of the reason that it has pointers is because we need to manage memory by ourselves, is that true? If true, how can we do that?
9 Respostas
+ 12
Memory allocated in the stack is managed automatically. But for memory in the heap, allocation and management is manual.
We use the 'new' keyword to allocate memory dynamically and use pointers to point to addresses in which memory has been allocated to, and the 'delete' keyword to free said memory.
+ 5
@Edson You only need to delete something which you have manually allocated to the heap. E.g.
int * my_var = new int;
delete my_var;
Normal variables do not require you to free them.
+ 1
Well, in a way yes. You have pointers and memory objects in c# as well, but c++ doesn't have any kind of automatic garbage collection or handles so what matters when you are working with pointers and memory is that you properly dispose and set your stuff to prevent memory leaks and other errors.
This is something you learn working with the language, I suggest you read about how memory works in general before trying to work with it.
If i'm unclear just ask and i'll try to explain further, this is a very simple version about it.
Remember that you can work with memory in c# it's just a lot more work.
0
Ok, that makes it more clear. thx
0
just in case it is unclear to you, you don't actually manage memory addresses in the hexadecimal way. you create a pointer variable to some part of the memory (which part of the memory you will get is, mostly, automatic) and then handle that pointer. however, you can just as well create normal variables (int x = 5), like c#. what has been said in the other posts still stands, of course. you need to delete pointers that you are not going to use.
to understand pointers more easily, think of system resources (hard disk space, CD roms, etc). if you opened a file, you would have to close it, right? RAM is one such resource. while many processes can have saved values in RAM, it still needs to be released after you are done with what you need.
0
sizizoz
- 1
so lets say I declared a var without using a pointer, do i need to delete them manually or do i only need to do it only if i declare a var with a pointer.
- 1
No Gerbage collector and features like in .NET. This is why C++ is pain in the ass.
- 1
Use smart pointers if the situation allows it. Learn about unique_ptr shared_ptr etc. They are in c++11 and they are wrappers around your simple pointers. The overhead is at most cases almost none