Skip to content

unique_ptr

cppreference std::unique_ptr

std::unique_ptr::release and std::unique_ptr::reset

NOTE:

release: returns a pointer to the managed object and releases the ownership

reset: Replaces the managed object.

NOTE: unique_ptr release and delete the owned object:

u_ptr.reset(nullptr);

Implementation

NOTE: 很多问题,当阅读它的实现的时候,就非常任意理解了。

gcc/libstdc++-v3/include/bits/unique_ptr.h

std::unique_ptr<void>

stackoverflow Should std::unique_ptr be permitted

stackoverflow Why is shared_ptr legal, while unique_ptr is ill-formed?

The question really fits in the title: I am curious to know what is the technical reason for this difference, but also the rationale ?

std::shared_ptr<void> sharedToVoid; // legal;
std::unique_ptr<void> uniqueToVoid; // ill-formed;

A

It is because std::shared_ptr implements type-erasure, while std::unique_ptr does not.

std::unique_ptr return from function and test for null

stackoverflow C++ std::unique_ptr return from function and test for null

cppreference std::unique_ptr<T,Deleter>::operator bool

Exmaple

#include <iostream>
#include <memory> // for std::shared_ptr

class Resource
{
public:
    Resource()
    {
        std::cout << "Resource acquired\n";
    }
    ~Resource()
    {
        std::cout << "Resource destroyed\n";
    }
};

class Test
{
public:
    Test()
    {
        InitR();
    }
    void InitR()
    {
        Resource* R = new Resource();
        m_R = std::unique_ptr<Resource>(R);
    }
private:
    std::unique_ptr<Resource> m_R;
};

int main()
{
    Test t;
}