을 사용해야합니까? std::enable_shared_from_this
양식 this link을 방금 알았습니다.
그러나 아래 코드를 읽은 후에는 언제 사용해야할지 모르겠습니다. getptr()
를 호출하기 전에 기존 shared_ptr
이 없기 때문에 위의
우리는 언제 std :: enable_shared_from_this
try {
Good not_so_good;
std::shared_ptr<Good> gp1 = not_so_good.getptr();
} catch(std::bad_weak_ptr& e) {
// undefined behavior (until C++17) and std::bad_weak_ptr thrown (since C++17)
std::cout << e.what() << '\n';
}
코드는 "너무 좋지 않다"입니다. 그래서 좋은 일이되어야합니다 :
std::shared_ptr<Good> gp1 = std::make_shared<Good>(); // having a shared_ptr at the beginning
std::shared_ptr<Good> gp2 = gp1->getptr();
을 그러나, 나는 이미이 같은하지 난 단지 코드를 할 이유 shared_ptr
개체, 한 경우 : 나는 모든 std::enable_shared_from_this
을 필요로하지 않는다는 것을 의미 std::shared_ptr<Good> gp2 = gp1;
을. std::enable_shared_from_this
를 사용하여 내 의견으로는
, 우리는 the double-delete problem를 방지 할 수 있도록 하나 이상의 shared_ptr
객체가 같은 제어 블록이 있는지 확인하는 것입니다. 그러나 내가 처음에 shared_ptr
을 만들 것을 상기시켜야한다면. 왜 그냥 원시 포인터를 사용하는 대신 shared_ptr
개체를 사용하여 새로운 개체를 만들 것을 상기시키지 않습니까?
'void f (좋은 & g);/* ... */f (* gp1);/* ... */void f (좋은 & g) {/ * 지금 뭐? * /}' – milleniumbug
@milleniumbug 미안 해요 – Yves
'f'는 공유 포인터가 아니라 참조를 취하기 때문에'shared_ptr'에 접근 할 수 없습니다. 때때로 참조를 취하기 위해 변경할 수 있지만, 그러나 회원 함수가 아니라면 - this는 항상 미가공 포인터입니다. – milleniumbug