unique_ptr doesnt delete the object



1
2
3
4
5
6
7
8
struct test { int a; };
std::vector<test> b;
    b.push_back({3});
    {
        std::unique_ptr<std::vector<test>> p = nullptr;
        p.reset(&b);
    }
    std::cout << b.size();

hello, its strange the this snippet doesnt give run time error,
after a unique_ptr object is destroyed, this should give me segfault at this std::cout << b.size(); whats more, b.size() returns 1 which should be 0.

am i understanding it wrong?

also
std::cout <<&b
outputs a valid address
Last edited on
"Deleting" objects mean freeing the memory it is using so it can be used again.
@boost lexical cast

in cppreference it says

The object is disposed of using the associated deleter when either of the following happens:
the managing unique_ptr object is destroyed


but it didnt happen

> its strange the this snippet doesnt give run time error,
it is undefined behaviour.


> whats more, b.size() returns 1 which should be 0.
¿why?
b has automatic storage duration. It doesn't make sense for it to be owned by a unique pointer.

You cannot invoke delete on an object with automatic storage duration. This is done by the default deleter when the stack unwinds on line 7. If your program happens to survive that, it's also undefined behavior to use an object whose lifetime has ended.

this should give me segfault
There is no requirement that you get a segfault, and expecting one (or any error at all) is a mistake. Your program exhibits undefined behavior, but that doesn't mean that you'll get any error at all. "Not getting an error" doesn't mean that your program is correct.

&b might output an address, but it's not a valid address.
Last edited on
@ne555

¿why?

because when p is destroyed, then the object it is pointing to will be destroyed too, so the vector will be deallocated and size will be 0. can you correct if im wrong??
@mbozzie i see thanks for that

so i did this
1
2
3
4
5
6
std::cout << &b;
{
        std::unique_ptr<std::vector<test>> p = nullptr;
        p.reset(&b);
}
std::cout << &b;

it outputs same address, but at line 6 the adress will become invalid i see
Last edited on
when p is destroyed, then the object it is pointing to will be destroyed too

destroyed, to be specific, using the default deleter (since you didn't specify a different one), which simply calls delete on the managed pointer. Calling delete to the address of b is undefined behavior because that address was not obtained by a call to new.

If you're giving unique_ptr a pointer you did not obtain from new, you also need to give it a deleter that won't call delete. For example, a unique pointer holding FILE* obtained from fopen would also hold a pointer to fclose as the deleter.

the vector will be deallocated and size will be 0.

no, once a vector is destroyed, it does not have any size. It does not exist.
Topic archived. No new replies allowed.