user3208216
user3208216

Reputation: 94

Delete pointer after return statement

I ran into the following problem: I want to return a Y-coordinate, and after I returned it, it needs to be deleted.

Is there a way to do this, because I think I'm missing some major things here.

void setY(int y)
    {
        this->y = new(int); //pointing to new address
        *this->y = y; //change value of pointer
    }

    int getY()
    {
        return *y; //give the coordinate
        delete y; //what I want
        *y = NULL; //what I want
    }

Thank you in advance. If the question is not well described, please let me know.

Upvotes: 1

Views: 4224

Answers (4)

Mike Seymour
Mike Seymour

Reputation: 254471

Since you say you really do need to muck around with pointers as part of a learning exercise, you need to read the return value before deleting:

int result = *y;
delete y;
y = nullptr;    // NOT *y - that's been deleted
return result;

(If you're stuck with a historic version of C++, then write NULL or 0 instead of nullptr. nullptr is better though - it would have prevented the mistake in your code).

You should also check y before dereferencing it, and fix the memory leak you get when calling setY more than once. Since the class is managing a separate resource, you'll also need to carefully follow the Rule of Three to avoid further memory errors.

Hopefully, the point of this exercise is to show you how difficult pointer-juggling can be, and how much easier it is to use more idiomatic techniques - in this case, simply storing an int directly.

Upvotes: 2

Casper Beyer
Casper Beyer

Reputation: 2301

Something like this

int getY()
{
   int value = -1;

   if (y_ptr) {
      value = *y_ptr;
      y_ptr = nullptr;
   }

   return value;
}

However i must add that this is just plain abuse of pointers, don't do it.

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234715

Notwithstanding the design flaws, the simplest thing to do is to take a copy:

int getY()
{
    int ret = *y;
    delete y; //what I want
    /*No assignment to deferenced y is possible - you've deleted it*/
    y = nullptr; /*a further delete on y will be benign*/
    return ret;
}

Upvotes: 3

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145279

Simply change your data member type fromj int* to plain int.

Then store the value there, and return the value, no new stuff.

Additional tip: a get prefix is useful in a language with introspection such as Java or C#, but is not neccessary (just verbiage) in C++.

Upvotes: 3

Related Questions