Reputation: 47
typedef typedef struct _OBJTIME {
WORD wYear;
WORD wMonth;
WORD wDayOfWeek;
WORD wDay;
WORD wHour;
WORD wMinute;
WORD wSecond;
WORD wMilliseconds;
} OBJTIME
OBJTIME objTime; //Note, this objTime is modified other function
OBJTIME ObjectParent::returnObjTime() const
{
return objTime;
}
My question is:
if another class calls returnObjTime() function, like say:
OBJTIME t = objectP->returnObjTime()
I assume a new copy of OBJTIME struct will be created?
Do I need to delete the variable "t" when I'm done? will it create a memory leak?
Thanks.
Upvotes: 3
Views: 1066
Reputation: 1288
No, you're returning a copy of global objTime
, both the copy and the global have durations based on their scopes, this means that when their scope end they will be automatically released from memory.
Upvotes: 6
Reputation: 2091
You did not dynamically allocate
it, you do not need to manually delete
it. So no, there will be no leak here.
Although, as you said yourself, you are making a lot of copies here, which is obviously a bad idea performance-wise.
If your wish is to return a read-only copy of your object, you could do this:
const OBJTIME&
ObjectParent::returnObjTime() const
{
return objTime;
}
Then it doesn't matter that your object weights 100bytes or 100Mbytes.
Upvotes: 3
Reputation: 767
Here the answer:
1 - You are returning value by return by value method ,return objTime; and taking it into a local variable, so every time it will be a new local copy "t".
2 - You need not to worry to delete variable "t" because you are not allocating memory through new operator for "t" it will be deleted automatically once you will go out of scope of the function(local variable scope is within a function block).
delete is only requires when you will be doing something like :
OBJTIME *t = new OBJTIME
Upvotes: 2
Reputation: 13925
Answer 1: Yes, a new copy will be created with a lifetime based on the scope of calling the function.
Answer 2: No, you don't need to delete somethin you haven't created with new.
Upvotes: 4
Reputation:
It's a copy yes, but it's not created by new
, so you don't need to delete
it.
Upvotes: 5