Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

default value of a unique_ptr

I am having difficulty understanding default value of unique_ptr.
From the cpp reference I see that there are two constructors of unique_ptr that says it owns nothing
Does nothing mean nullptr?

constexpr unique_ptr() noexcept;
constexpr unique_ptr( std::nullptr_t ) noexcept;

I created an small example below. If I check for nullptr, it returns true. Is this behavior guaranteed?

#include <memory>
#include <vector>
#include <iostream>

class A {
  public:
    A(int i) :m_i(i) {}
    ~A() {}
    int getI() { return m_i; }
  private:
    int m_i;
};

int main() {
    std::unique_ptr<A> a;
    if(a == nullptr) {
     std::cout << "A is null\n";   
    }
    std::vector<std::unique_ptr<A>> vec;
    vec.resize(5);
    for(size_t i = 0; i < vec.size(); i++) {
        if(vec[i] == nullptr) {
            std::cout << "Nullptr" << std::endl;   
        }
    }
    return 0;
}

O/p of the above code in my system (gcc) is

A is null
Nullptr
Nullptr
Nullptr
Nullptr
Nullptr

If I check for null on an uninitialized unique_ptr, is it guaranteed that it will be nullptr? Or Is it implementation defined?

like image 407
Sourabh Avatar asked Mar 07 '21 15:03

Sourabh


People also ask

How big is a unique_ptr?

This means that unique_ptr is exactly the same size as that pointer, either four bytes or eight bytes.

What is a unique_ptr?

std::unique_ptr is a smart pointer that owns and manages another object through a pointer and disposes of that object when the unique_ptr goes out of scope. The object is disposed of, using the associated deleter when either of the following happens: the managing unique_ptr object is destroyed.

Does unique_ptr delete itself?

unique_ptr objects automatically delete the object they manage (using a deleter) as soon as they themselves are destroyed, or as soon as their value changes either by an assignment operation or by an explicit call to unique_ptr::reset.


1 Answers

For these two constructor overloads:

constexpr unique_ptr() noexcept;
constexpr unique_ptr(std::nullptr_t) noexcept;

The documentation says that these two constructors above create a std::unique_ptr object that owns nothing.

Now, by looking at the documentation of std::unique_ptr's get() member function:

Returns a pointer to the managed object or nullptr if no object is owned.

Since the std::unique_ptr objects that are created through any of those two constructors own nothing, we conclude that get() returns nullptr for these std::unique_ptr objects.

like image 114
ネロク・ゴ Avatar answered Sep 27 '22 23:09

ネロク・ゴ