Lets consider such example:
typedef struct {
int hours;
int minutes;
int seconds;
} Time;
Time createTime() {
Time time;
time.hours = ....
time.hours = ....
time.hours = ....
return time
}
void doSomething(){
while(true){
Time newTime = createTime();
// do something with time....
}
}
I have few questions about memory allocation
createTime() does not return NULL? The #time is a local variable so it should be destroyed when method goes out of scope. doSomething() I am calling createTime() multiple times, will this create memory leak? createTime cannot do return NULL; - it returns a Time.
Functions return by value in C and C++. This means that when you write return time;, there is a temporary object created called the return value. This is copied from the expression you return. In C this is member-wise copy, in C++ it uses the copy-constructor. So the sequence of events for the code Time newTime = createTime(); is:
time inside createTime() is created and populatedtime
time is destroyednewTime is created, with the return value used as initializer.Now this is in principle a lot of copying and destroying, but the compiler is permitted to optimize it (in both C and C++) so that the end result is that createTime can construct time directly into the memory space of newTime, with no temporaries needed. In practice you may find various levels of optimization applied.
NB. In C++11 replace copy with copy or move in the above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With