c++ - 如何将原始指针包装到 shared_ptr 中并防止 shared_ptr 删除对象?

标签 c++ shared-ptr

我需要将原始指针包装到 shared_ptr 中,以便将其传递给函数。该函数在返回后不保留对输入对象的任何引用。

{
  MyClass i;
  shared_ptr<MyClass> p(&i);
  f(p);
  // BAD: shared_ptr will delete i.
}

如何防止shared_ptr删除引用的对象?

最佳答案

作为chris在评论中提到,写一个空的删除器:

#include <type_traits>

template <typename T>
struct empty_delete
{
    empty_delete() /* noexcept */
    {
    }

    template <typename U>
    empty_delete(const empty_delete<U>&,
        typename std::enable_if<
            std::is_convertible<U*, T*>::value
        >::type* = nullptr) /* noexcept */
    {
    }

    void operator()(T* const) const /* noexcept */
    {
        // do nothing
    }
};

使用示例:

#include <iostream>
#include <memory>

struct noisy
{
    noisy() { std::cout << "alive" << std::endl; }
    ~noisy() { std::cout << "dead" << std::endl; }

    noisy(const noisy&);
    noisy& operator=(const noisy&);
};

template <typename T>
void take(T& yours)
{
    std::cout << "Taking..." << std::endl;
    {
        auto mine = std::move(yours);
    }
    std::cout << "Took." << std::endl;
}

int main()
{
    std::unique_ptr<noisy> a(new noisy());
    std::shared_ptr<noisy> b(new noisy());
    std::unique_ptr<noisy, empty_delete<noisy>> c(new noisy());
    std::shared_ptr<noisy> d(new noisy(), empty_delete<noisy>());

    take(a);
    take(b);
    take(c);
    take(d);
}

输出:

alive
alive
alive
alive
Taking...
dead
Took.
Taking...
dead
Took.
Taking...
Took.
Taking...
Took.

当然,这个例子会泄漏内存。

关于c++ - 如何将原始指针包装到 shared_ptr 中并防止 shared_ptr 删除对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15534146/

相关文章:

C++ 链接器错误 LNK2001 和 LNK1120 Winsock2 Lib

c++ - 如何使用 QFileDialog 和 boost 保存多张图片

c++ - 英特尔 AVX 内在函数 : any compatibility library out?

c++ - 子类的成员函数指针

c++ - 尝试使用线程运行 CamShift

c++ - 如何制作包含共享指针列表的对象的拷贝?

c++ - 在函数中使用指向类的 const 指针

c++ - 如何将共享指针设置为常规指针

c++ - 对象构造后 shared_from_this 中的 std::bad_weak_ptr 异常

c++ - std::bind 与 std::shared_ptr