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

Passing 0 to the shared pointer with deleter as the first argument

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

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 版本的错误,而不是当前标准版本。