But what is the point of dynamic memory for a single type?
What would you prefer? A minimum size permitted for dynamic memory?
Moschops
Practically a Master Poster
620 posts since Sep 2008
Reputation Points: 258
Solved Threads: 117
>>Do you mean if i were to declare an object with dynamic memory within a particular function it would be available within another function?
Yes, if you provide the pointer as a result of the function for example.
Generally, this is not recommended, but sometimes hard to avoid. If you do that, it is also recommended that you use a smart-pointer instead of a simple pointer (or raw pointer).
In concrete terms:
int* give_pointer() {
return new int(42);
};
int main() {
int* pi = give_pointer();
// now, the value can be accessed from outside the function, through pi:
std::cout << " The value is: " << *pi << std::endl;
// now, here's the nasty part, you have to delete the pointer yourself:
delete pi; //But, what if it was created with malloc()? What if it was a static variable? This line could cause a crash...
return 0;
};
Normally, you would, instead, provide an additional function to deallocate the object. The point of all this is that the life-time of the object is from point of the "new" call up to the point of the "delete" call, so, it is not bound to an automatic scope like local variables (which, simply speaking, are created when you enter the function and get destroyed when you leave it).
Better yet, you use a smart-pointer whose job is to delete the object when noone needs it anymore (this is what std::shared_ptr does).
Another use for allocating one object at a time is for doing dynamic polymorphism, e.g., to create an object of one class and provide it as a base-class pointer. But I have the feeling you are not there yet in your learning / book-reading, so, leave that aside for now.
mike_2000_17
Posting Virtuoso
2,139 posts since Jul 2010
Reputation Points: 1,634
Solved Threads: 458
But what is the point of dynamic memory for a single type?
Exactly...
For a single type, it's a waste to use dynamic memory. I can't think of any reason why one would need to dynamically create anint or float.
Do you mean if i were to declare an object with dynamic memory within a particular function it would be available within another function?
If you pass it to the function, sure...
WaltP
Posting Sage w/ dash of thyme
10,506 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944