1

I have one question. Is it possible to delete a pointer with function? This is my example:

void deletePointer(auto* pointer)
{
    delete pointer;
    pointer = nullptr;
}

int main()
{
    int value = 5;
    int* value_ptr = &value;

    //Some code

    deletePointer(value_ptr);

    return 0;
}

And it doesn't work. I also tried adding "inline" keyword to function and with lambda.

auto deletePointer = [&](auto* pointer) -> void
{
    delete pointer;
    pointer = nullptr;
}

I think it only deletes pointer inside of function, lambda. Is it possible to make function that will delete pointer, which is passing to function?

  • 3
    You can only `delete` what you `new`ed, your first snippet is invalid. – Mat Apr 05 '20 at 16:34
  • 2
    Also, you don't want to pass the pointer 'by value' if you want to edit where it is pointing. If you declare deletepointer as "void deletePointer(auto * & pointer), you can let it point to nullptr outside the scope of the function, in case you're wondering why value_ptr == nullptr is false . – mutableVoid Apr 05 '20 at 16:39
  • 1
    Oh, you're right. This solves my problem. Thanks :) – Miłosz Brzechczyn Apr 05 '20 at 16:39
  • Also I have another question. Am I supposed to delete pointers which are pointing a variable (without `new`)? – Miłosz Brzechczyn Apr 05 '20 at 16:43
  • 1
    @MiłoszBrzechczyn no you must not delete pointers allocated on the stack, as Mat indicated, see for instance the answer in [this post](https://stackoverflow.com/questions/441831/calling-delete-on-variable-allocated-on-the-stack). Even more, even if used correctly, raw pointers are to be avoided, as they are in most cases considered code-smells, and to be replaced my more modern memory management – mutableVoid Apr 05 '20 at 16:51
  • 1
    @MiłoszBrzechczyn for the future: If you come up with an answer to your own question, it is easier for others who encounter a similar problem if you post your answer separate from the question in the answer area, and leave the question itself unchanged. After a certain time passed, you're then able to accept you're own answer, s.th. it is shown with a green answer check mark. – mutableVoid Apr 05 '20 at 16:59
  • 1
    Ok, thanks. I will do it. – Miłosz Brzechczyn Apr 05 '20 at 17:01
  • I got message: "You can accept your own answer in 2 days". So I must wait. – Miłosz Brzechczyn Apr 05 '20 at 17:11

1 Answers1

2

Solution.

I got to know that delete can be used only when object is creating using new. So I changed code a bit.

#include <iostream>

void deletePointer(auto*& pointer)
{
    delete pointer;
    pointer = nullptr;
}

int main()
{
    int* ptr = new int(5);

    deletePointer(ptr);

    if (ptr == nullptr) std::cout << "Succeed";
    else std::cout << "Failed";

    return 0;
}

And given output from code is: Succeed. So now everything works. Thanks for help :)