本文介绍了是否将默认构造的(空)shared_ptr自动初始化为nullptr?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从某个博客中了解到,默认构造的(空) shared_ptr 被自动初始化为 nullptr .但是在标准中找不到任何这样的明确声明.

I had read from some blog that a default-constructed (empty) shared_ptr is automatically initialized to nullptr. But could not find any such explicit statement in the statndards.

我写了一个小片段(Linux编译)来确认这一点:

I wrote a small snippet (Linux Compiled) to confirm this:

#include <iostream>
#include <memory>

struct Base;

int main()
{
    std::shared_ptr<Base> p;
    Base* b;

    if (p == nullptr) {
        std::cout << "p IS NULL \n";
    }
    else {
        std::cout << "p NOT NULL \n";
    }

    if (b == nullptr) {
        std::cout << "b IS NULL \n";
    }
    else {
        std::cout << "b NOT NULL \n";
    }

    return 0;
}
p IS NULL

b NOT NULL

由此我看到,在声明时智能指针被隐式分配了 nullptr .有人可以确认这种行为吗?使用 shared_ptr 而不手动为其分配 nullptr 是否安全?

From this I see that the smart pointers are implicitly assigned nullptr at the time of Declaration. Can somebody confirm this behavior? Is it safe to use a shared_ptr without manually assigning a nullptr to it?

推荐答案

是的, cppreference 告诉我们,默认构造函数与只将 nullptr 传递给构造函数相同:

Yes, cppreference tells us that the default constructor is identical to just passing a nullptr to the constructor:

constexpr shared_ptr() noexcept;                        (1)
constexpr shared_ptr( std::nullptr_t ) noexcept;        (2)

也来自 C ++标准草案2017 :

...

constexpr shared_ptr()noexcept;
   2 效果:构造一个空的 shared_ptr 对象.
   3 后置条件: use_count()== 0&&get()== nullptr .

constexpr shared_ptr() noexcept;
  2 Effects: Constructs an empty shared_ptr object.
  3 Postconditions: use_count() == 0 && get() == nullptr.

这篇关于是否将默认构造的(空)shared_ptr自动初始化为nullptr?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-01 13:12