查看 std::unique_ptr 及其nullptr_t构造函数
Looking at std::unique_ptr and its nullptr_t constructor
我试图理解为什么unique_ptr
有一个nullptr_t构造函数
constexpr unique_ptr::unique_ptr( nullptr_t );
我假设这是因为正常的 one 参数构造函数是显式的,因此会拒绝 nullptr 值:
explicit unique_ptr::unique_ptr( pointer p );
但是当我构建一个示例时,编译器很好:
namespace ThorsAnvil
{
template<typename T>
class SmartPointer
{
public:
SmartPointer() {}
explicit SmartPointer(T*){}
};
}
template<typename T>
using SP = ThorsAnvil::SmartPointer<T>;
int main()
{
SP<int> data1;
SP<int> data2(new int); // fine
SP<int> data3(nullptr); // fine
}
这是输出:
> g++ --version
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 6.0 (clang-600.0.56) (based on LLVM 3.5svn)
Target: x86_64-apple-darwin14.0.0
Thread model: posix
> g++ -Wall -Wextra -std=c++11 SP1.cpp
为什么 std::unique_ptr 需要接受nullptr_t参数的额外构造函数?
SP<int> data3(nullptr); // fine
您使用的是直接初始化,这会导致考虑explicit
构造函数。请尝试以下操作,但代码无法编译
SP<int> data4 = nullptr;
现在添加以下构造函数,上面的行将编译
SmartPointer(std::nullptr_t){}
因此,nullptr_t
构造函数使unique_ptr
在您想要将其初始化为nullptr
的情况下表现得像原始指针,但在您可能实际为其分配原始指针的其他情况下避免任何令人惊讶的所有权转移。
相关文章:
- "error: no matching function for call to"构造函数错误
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 选择要调用的构造函数
- 如何委托派生类使用其父构造函数?
- 构造函数正在调用一个使用当前类类型的函数
- 没有用于初始化C++中的变量模板的匹配构造函数
- 初始化具有非默认构造函数的std::数组项的更好方法
- 当从函数参数中的临时值调用复制构造函数时
- 在c++构造函数中使用随机字符串生成器
- 一对向量构造函数:初始值设定项列表与显式构造
- 从构造函数抛出异常时如何克服内存泄漏
- 我不明白为什么我声明一个空的内部结构并将其传递给构造函数
- 具有显式定义的默认构造函数的 unique_ptr 到 nullptr 错误的类内成员初始值设定项
- 函数构造函数和nullptr
- 如何防止客户端将nullptr传递给构造函数
- "using" (typedef) 指针:它的默认构造函数返回 nullptr?
- 为什么显式构造函数期望 std::shared_ptr 接受 nullptr