简体   繁体   中英

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.

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++.

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;
}

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM