Miłosz Brzechczyn
Miłosz Brzechczyn

Reputation: 98

C++ Deleting pointer with function

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?

Upvotes: 1

Views: 461

Answers (1)

Miłosz Brzechczyn
Miłosz Brzechczyn

Reputation: 98

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 :)

Upvotes: 2

Related Questions