c++ - 将 0 传递给共享指针,删除器作为第一个参数

标签 c++ smart-pointers

我正在阅读 Scott Meyrse C++,现在我正在阅读关于设计接口(interface)的部分。以下代码应该是无效的:

std::tr1::shared_ptr<Investment> // attempt to create a null
pInv(0, getRidOfInvestment);     // shared_ptr with a custom deleter;
                                 // this won’t compile

他给出了如下解释:

The tr1::shared_ptr constructor insists on its first parameter being a pointer, and 0 isn’t a pointer, it’s an int. Yes, it’s convertible to a pointer, but that’s not good enough in this case; tr1::shared_ptr insists on an actual pointer.

我自己试过类似的例子http://coliru.stacked-crooked.com/a/4199bdf68a1d6e19

#include <iostream>
#include <memory>

struct B{
    explicit B(void *){ }
};

void del(int*){ }
int main()
{
    B b(0);
    std::shared_ptr<int*> ptr(0, del);
}

即使将 0 作为第一个参数传递,它也能正常编译和运行。

他到底是什么意思?这不是已经相关了吗?

最佳答案

一个来自#include <tr1/memory> ;另一个来自#include <memory> .有区别:

http://coliru.stacked-crooked.com/a/f76ea0ef17227d9d

#include <iostream>
#include <tr1/memory>
#include <memory>

struct B{
    explicit B(void *){ }
};

void del(int*){ }
int main()
{
    B b(0);
    std::tr1::shared_ptr<int*> ptr(0, del);
    std::shared_ptr<int*> ptr2(0, del);
}

它给出了 tr1 的错误版本,但不是当前的标准版本。

关于c++ - 将 0 传递给共享指针,删除器作为第一个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33006346/

相关文章:

C++:char* 与 char(*)[]

c++ - 为什么 ShellExecute()ing cmd.exe 隐藏有效?

c++ - 将常量传播到成员变量指向的数据

c++ - 从继承自 std::enable_shared_from_this 的类继承后的 std::bad_weak_ptr

c++ - 智能指针包装 CoTaskMemAlloc 和 CoTaskMemFree

c++ - 带有用 C 编写的库的智能指针

c++ - 函数和多态性中的默认参数

c++ - 返回 char 数组作为 std :string

c++ - 复制构造函数中初始化列表中的 make_unique 是不使用 noexcept 说明符的良好目的吗?

c# - 是否可以定义在系统范围内使用的自定义 URI 方案?