|
|
|
|
int* h_value = new int;delete h_value; // identifier "h_value" is undefined | Because h_value was on the stack, and it went out of scope, so no longer exists. What it was pointing to still exists, on the heap. |
| So in this case, does delete actually need to be called at all? I thought it was necessary to always call delete if new was previously called. |
int* h_arr = new int[5];, two things are created, like Repeater said.
new int[5]:
+--------+---------+--------+-------+--------+
| | | | | |
| | | | | |
| | | | | |
+-----------+ | | | | | |
| | | | | | | |
| h_value +------------>+ | | | | |
| | | | | | | |
+-----------+ | | | | | |
| | | | | |
| | | | | |
| | | | | |
+--------+---------+--------+-------+--------+ |
new int[5]:
+--------+---------+--------+-------+--------+
| | | | | |
| | | | | |
| | | | | |
| | | | | |
| | | | | |
| | | | | |
| | | | | |
| | | | | |
| | | | | |
| | | | | |
| | | | | |
+--------+---------+--------+-------+--------+ |
std::string, std::vector, std::unique_ptr, std::shared_ptr, etc. |
|
| keskiverto wrote: |
|---|
| Size of stack allocations is static constant that must be known at compile-time |
|
|
| what are the actual benefits of heap allocation? |
| heap alloctated memory may exists longer than the encompassing function. A local variable does not. Hence somethimes it is inevitable to use dynamic allocated objects. |
| calioranged wrote: |
|---|
| I am just getting used to the concept of heap allocation so feel free to correct me if there is something that I have overlooked, but it seems to me that extending the lifetime of an object beyond the scope it was created within via heap allocation is actually a drawback rather than a benefit, and requires some cleaning up as well that can lead to further complications. |
| but it seems to me that extending the lifetime of an object beyond the scope it was created within via heap allocation is actually a drawback rather than a benefit |
| Correct. Heap allocation should be avoided and should only be done when there is no other way. |
| You can have several pointers to the same heap allocated object. So if one pointer goes out of scope, there could be other pointers still pointing to the memory thinking it's valid. |
|
|
|
|
|
|
| Yes, but don't do this in modern C++. Just return an std::vector. Heap allocation itself isn't that bad, what's bad is managing it yourself when you don't have to (i.e. calling new/delete yourself). |