默认构造的(空)shared_ptr会自动初始化为nullptr吗?
Will a default-constructed (empty) shared_ptr automatically be initialized to nullptr?
我从一些博客上读到,默认构造的(空)shared_ptr
会自动初始化为 nullptr
。但是在标准中找不到任何这样的明确声明。
我写了一个小片段(Linux 编译)来证实这一点:
#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;
}
Output:
p IS NULL
b NOT NULL
由此可见智能指针在声明时被隐式赋值nullptr
。有人可以确认这种行为吗?使用 shared_ptr
而不手动分配 nullptr
是否安全?
是的,cppreference 告诉我们默认构造函数与仅将 nullptr
传递给构造函数相同:
constexpr shared_ptr() noexcept; (1)
constexpr shared_ptr( std::nullptr_t ) noexcept; (2)
1-2) Constructs a shared_ptr with no managed object, i.e. empty shared_ptr
也来自 C++ standard draft for 2017:
23.11.2.2.1 shared_ptr
constructors
...
constexpr shared_ptr() noexcept;
2 Effects: Constructs an empty shared_ptr
object.
3 Postconditions: use_count() == 0 && get() == nullptr
.
[util.smartptr.shared.const]/3
中对此进行了介绍
Ensures: use_count() == 0 && get() == nullptr
.
我从一些博客上读到,默认构造的(空)shared_ptr
会自动初始化为 nullptr
。但是在标准中找不到任何这样的明确声明。
我写了一个小片段(Linux 编译)来证实这一点:
#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;
}
Output:
p IS NULL b NOT NULL
由此可见智能指针在声明时被隐式赋值nullptr
。有人可以确认这种行为吗?使用 shared_ptr
而不手动分配 nullptr
是否安全?
是的,cppreference 告诉我们默认构造函数与仅将 nullptr
传递给构造函数相同:
constexpr shared_ptr() noexcept; (1)
constexpr shared_ptr( std::nullptr_t ) noexcept; (2)
1-2) Constructs a shared_ptr with no managed object, i.e. empty shared_ptr
也来自 C++ standard draft for 2017:
23.11.2.2.1
shared_ptr
constructors...
constexpr shared_ptr() noexcept;
2 Effects: Constructs an emptyshared_ptr
object.
3 Postconditions:use_count() == 0 && get() == nullptr
.
[util.smartptr.shared.const]/3
中对此进行了介绍Ensures:
use_count() == 0 && get() == nullptr
.