your programing

이것에 대한 boost :: shared_ptr 얻기

lovepro 2020. 10. 16. 07:52
반응형

이것에 대한 boost :: shared_ptr 얻기


boost:shared_ptr내 코드에서 광범위하게 사용 하고 있습니다. 실제로 힙에 할당 된 대부분의 개체는 shared_ptr. 나는 통과 할 수없는 불행하게도이 방법 this소요 어떤 함수로 shared_ptr. 이 코드를 고려하십시오.

void bar(boost::shared_ptr<Foo> pFoo)
{
    ...
}

void Foo::someFunction()
{
    bar(this);
}

여기에는 두 가지 문제가 있습니다. 첫째,의 T * 생성자 shared_ptr가 명시 적이기 때문에 컴파일되지 않습니다 . 둘째, 강제로 빌드하면 bar(boost::shared_ptr<Foo>(this))객체에 대한 두 번째 공유 포인터가 생성되어 결국 이중 삭제가 발생합니다.

이것은 내 질문으로 이어집니다. 기존 공유 포인터의 복사본을 해당 객체 중 하나의 메서드 내부에서 가져 오는 표준 패턴이 있습니까? 여기에 침입 참조 계산을 사용하는 유일한 옵션이 있습니까?


enable_shared_from_this 에서 파생 된 다음 "this"대신 "shared_from_this ()"를 사용하여 자체 객체에 대한 공유 포인터를 생성 할 수 있습니다.

링크의 예 :

#include <boost/enable_shared_from_this.hpp>

class Y: public boost::enable_shared_from_this<Y>
{
public:

    shared_ptr<Y> f()
    {
        return shared_from_this();
    }
}

int main()
{
    shared_ptr<Y> p(new Y);
    shared_ptr<Y> q = p->f();
    assert(p == q);
    assert(!(p < q || q < p)); // p and q must share ownership
}

멤버 함수에서 스레드를 생성 할 때 this 대신 shared_from_this ()로 boost :: bind하는 것이 좋습니다. 개체가 해제되지 않도록합니다.


shared_ptr 대신 함수 매개 변수에 원시 포인터를 사용하십시오. 스마트 포인터의 목적은 개체의 수명을 제어하는 ​​것이지만 개체 수명은 이미 C ++ 범위 지정 규칙에 의해 보장됩니다. 적어도 함수가 끝날 때까지 존재합니다. 즉, 호출 코드는 함수가 반환되기 전에 개체를 삭제할 수 없습니다. 따라서 함수 내에서 개체를 삭제하지 않는 한 "벙어리"포인터의 안전이 보장됩니다.

shared_ptr을 함수에 전달해야하는 유일한 경우는 객체의 소유권을 함수에 전달하거나 함수가 포인터의 복사본을 만들려고 할 때입니다.


boost에는이 사용 사례에 대한 솔루션이 있습니다. enable_shared_from_this를 확인하십시오.


정말 바 안에 pFoo의 더 많은 공유 사본을 만들고 있습니까? 내부에서 미친 짓을하지 않는다면 다음과 같이하십시오.


void bar(Foo &foo)
{
    // ...
}

C ++ 11 shared_ptr함께 enable_shared_from_this이제 표준 라이브러리에 있습니다. 이름에서 알 수 있듯이 후자는 정확히이 경우입니다.

http://en.cppreference.com/w/cpp/memory/shared_ptr

http://en.cppreference.com/w/cpp/memory/enable_shared_from_this

위 링크의 예는 다음과 같습니다.

struct Good: std::enable_shared_from_this<Good>{
    std::shared_ptr<Good> getptr() {
        return shared_from_this();
    }
};

사용하다:

std::shared_ptr<Good> gp1(new Good);
std::shared_ptr<Good> gp2 = gp1->getptr();
std::cout << "gp2.use_count() = " << gp2.use_count() << '\n';

포인터를받는 함수는 두 가지 동작 중 하나를 수행하려고합니다.

  • 전달 되는 개체를 소유하고 범위를 벗어나면 삭제합니다. 이 경우 X *를 받아들이고 즉시 해당 객체 주위에 scoped_ptr을 감쌀 수 있습니다 (함수 본문에서). 이것은 "this"또는 일반적으로 힙 할당 된 객체를 받아들이도록 작동합니다.
  • Share a pointer (don't own it) to the object being passed in. In this case you do not want to use a scoped_ptr at all, since you don't want to delete the object at the end of your function. In this case, what you theoretically want is a shared_ptr (I've seen it called a linked_ptr elsewhere). The boost library has a version of shared_ptr, and this is also recommended in Scott Meyers' Effective C++ book (item 18 in the 3rd edition).

Edit: Oops I slightly misread the question, and I now see this answer is not exactly addressing the question. I'll leave it up anyway, in case this might be helpful for anyone working on similar code.

참고URL : https://stackoverflow.com/questions/142391/getting-a-boostshared-ptr-for-this

반응형