A special use of shared_ptr

As we all know, shared_ptr is a commonly used smart pointer, which is usually used.

#include "stdafx.h"
#include <iostream>
#include <future>
#include <thread>

using namespace std;
class Person
{
};

int main()
{
    std::shared_ptr<Person> p1(new Person(1));// Person(1)的引用计数为1
    return 0;
}

    As above, when the smart pointer is destructed, the real pointer will also be destructed. What if we want the smart pointer to be destructed, but the real pointer will not be destructed?

    

class RemoveOnDelete {
    OpTracker *tracker;
public:
    RemoveOnDelete(OpTracker *tracker) : tracker(tracker) {}
    void operator()(TrackedOp *op);
};

template <typename T, typename U>
typename T::Ref create_request(U params)
{
    typename T::Ref retval(new T(params, this),
			   RemoveOnDelete(this));
    return retval;
}

    Before ceph saw this code, it always felt strange. typename T::Ref is a smart pointer, but it takes 2 parameters. And when the smart pointer reference is decremented to 0, the memory of the actual pointer is not really freed. So I wrote a code test myself:

include <iostream>
#include <set>
#include <boost/shared_ptr.hpp>
using namespace std;
class a;
typedef std::shared_ptr<a> a_ptr;

class a {
};
class b {
public:
  void operator()(a *)
  {
    cout<< "haha" << endl;
  }
};
void test(a_ptr& c)
{
    cout << "hello world" << endl;
}
int main()
{
    a_ptr d(new a(), b());
    test(d);
    d.reset();
    return 0;
}

    Among them, class b must implement the overloading of the () operator, and must use the pointer a as the only parameter, otherwise the compilation will report an error. haha is printed when d.reset() is executed. It can be seen that void operator()(a *) is executed when d is released.

    When we don't want to actually release an allocated memory, but we want to ensure that it will not be used, we can use the above method

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325304502&siteId=291194637