user1943292
user1943292

Reputation: 47

In C++, if a function returns a struct, do I need to delete the struct after using it?

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:

  1. if another class calls returnObjTime() function, like say:

    OBJTIME t = objectP->returnObjTime()
    I assume a new copy of OBJTIME struct will be created?

  2. Do I need to delete the variable "t" when I'm done? will it create a memory leak?

Thanks.

Upvotes: 3

Views: 1066

Answers (5)

Luke B.
Luke B.

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

cmc
cmc

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

Astro - Amit
Astro - Amit

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

Matzi
Matzi

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

user334856
user334856

Reputation:

It's a copy yes, but it's not created by new, so you don't need to delete it.

Upvotes: 5

Related Questions