Effective Modern C++ Study
C++ Korea
Item 20 :
Item 20: Use std::weak_ptr for std::shared_ptr - like pointers that can dangle.
발표자 : 정은식
Effective Modern C++ Study
C++ Korea3
lstd::shared_ptr 은 좋은 스마트 포인터이지만...
l스마트 포인터는 파괴된 포인터를 가르킬 경우 경쟁하는 문제점
이있음.
lshared_ptr을 보강하기 위해 std::weak_ptr 등장..
l특징
l1)weak_ptr은 reference 카운터에 영향을 안줌.
l2)std::weak_ptr은 역 참조 , nullnes 테스트 할수있다.
3
Effective Modern C++ Study
C++ Korea4
lstd::weak_ptr 는 shard_ptr 을 도와주는 포인터..
4
swp reference count : 1
소멸자 호출
on dangles pointer
Effective Modern C++ Study
C++ Korea5
latomic 연산을 하고싶으면 weak_ptr로 체크후 객체를 point로 액세스
해야합니다..
l1) std::shared_ptr<Widget> spw1 = wpw.lock();
lauto spw2 = wpw.lock();
l//// if wpw's expired, is null
l2)std::shared_ptr<Widget> spw3(wpw);
l////if wpw's expired throw std::bad_weak_ptr
5
Effective Modern C++ Study
C++ Korea6
l shard_ptr 순환참조 문제 ..
6
lb의 참조방식이.. 3가지 경우..
lraw pointer : A가 파괴됬을떄 B는 A가 dangle 포인터
인지 감지 불가능하고 참조했을경우.정의되지 않은
행동을 함..
lshared_ptr : a는 b참조 b는 a참조
l이 디자인은 a,b 모두 파괴를 방지하여 누수가 일어
남
lA std::weak_ptr 은 저 두 문제를 피하기 가능.
la,b는 서로 가르키지만 b의 포인터의 참조는 영향을
안줌
Effective Modern C++ Study
C++ Korea77
Effective Modern C++ Study
C++ Korea9
template<typename T, typename... Ts>
std::unique_ptr<T> make_unique(Ts&&... params)
{
return std::unique_ptr<T>(new T(std::forward<Ts>(params)...));
}
Effective Modern C++ Study
C++ Korea10
template <class T, class... Args> unique_ptr<T>
make_unique(Args&&... args);
template <class T> unique_ptr<T> make_unique(size_t n);
template <class T, class... Args> unspecified
make_unique(Args&&...) = delete;
Effective Modern C++ Study
C++ Korea11
auto upw1(std::make_unique<Widget>()); // with make func
std::unique_ptr<Widget> upw2(new Widget); // without make func
auto spw1(std::make_shared<Widget>()); // with make func
std::shared_ptr<Widget> spw2(new Widget); // without make func
Effective Modern C++ Study
C++ Korea12
processWidget(std::make_shared<Widget>(), // no potential
computePriority()); // resource leak
Effective Modern C++ Study
C++ Korea13
Effective Modern C++ Study
C++ Korea14
std::unique_ptr<Widget, decltype(widgetDeleter)>
upw(new Widget, widgetDeleter);
std::shared_ptr<Widget> spw(new Widget, widgetDeleter);
Effective Modern C++ Study
C++ Korea15
// create std::initializer_list
auto initList = { 10, 20 };
// create std::vector using std::initializer_list ctor
auto spv = std::make_shared<std::vector<int>>(initList);
Effective Modern C++ Study
C++ Korea16
Effective Modern C++ Study
C++ Korea17
Effective Modern C++ Study
C++ Korea18
class ReallyBigType { … }; // as before
std::shared_ptr<ReallyBigType> pBigObj(new ReallyBigType);
// create very large
// object via new
Effective Modern C++ Study
C++ Korea19
std::shared_ptr<Widget> spw(new Widget, cusDel);
processWidget(spw, computePriority()); // correct, but not
// optimal; see below
processWidget(std::move(spw), // both efficient and
computePriority()); // exception safe
Effective Modern C++ Study
C++ Korea20
이 자료는 개념을 설명하기 위해 책 내용 이외에 더 많은 내용을 조사해 포함
하였으며, 오류가 있을 수 있음을 미리 알립니다.
오류 : fb.com/bighilljae, hanjae.jea@gmail.com
22
Effective Modern C++ Study
C++ Korea
Identity
Ex) int a;
identity X
Live long
Effective Modern C++ Study
C++ Korea24
25
Effective Modern C++ Study
C++ Korea
생성자에서 데이터를 가져올 parameter가 std::string이다.
parameter를 받으면서 복사 연산이 수행된다.
Effective Modern C++ Study
C++ Korea27
Text값을 변경 하지 않으니 const를 붙여주자. @EC++
cons : std::string 객체를 복사하는 비용이 크게 발생함.
Effective Modern C++ Study
C++ Korea28
Text 는 value에 move 되지 않고 copy 된다.
Text가 const string인 관계로 cast 결과는 rvalue const string
Effective Modern C++ Study
C++ Korea29
1. std::move(text)가 rvalue const string이었다.
2. Constness를 유지하기 위해 copy constructor 로 동작함.
3. Const string을 non-const rvalue-reference에 넣을 수 없다.
30
Effective Modern C++ Study
C++ Korea31
Effective Modern C++ Study
C++ Korea32
• 기대했던 동작은 lvalue, rvalue 맞추어
서 process 실행
• 하지만 param이 function parameter 라
서 lvalue이다.
• Param이 rvalue가 되도록 하는 동작이
필요하다.
• 핵심은 move, forward가 cast를 무조건,
조건적으로 한다는 것
• Forward만 써도 되지 않나요? 예, 사실
그래도 되는데, 장점이 있습니다.
Forward는 매번 타입이 필요하지만
move는 그렇지 않아요.
Effective Modern C++ Study
C++ Korea33
감사합니다

[C++ korea] Effective Modern C++ 신촌 Study Item20,21,23

  • 1.
    Effective Modern C++Study C++ Korea
  • 2.
    Item 20 : Item20: Use std::weak_ptr for std::shared_ptr - like pointers that can dangle. 발표자 : 정은식
  • 3.
    Effective Modern C++Study C++ Korea3 lstd::shared_ptr 은 좋은 스마트 포인터이지만... l스마트 포인터는 파괴된 포인터를 가르킬 경우 경쟁하는 문제점 이있음. lshared_ptr을 보강하기 위해 std::weak_ptr 등장.. l특징 l1)weak_ptr은 reference 카운터에 영향을 안줌. l2)std::weak_ptr은 역 참조 , nullnes 테스트 할수있다. 3
  • 4.
    Effective Modern C++Study C++ Korea4 lstd::weak_ptr 는 shard_ptr 을 도와주는 포인터.. 4 swp reference count : 1 소멸자 호출 on dangles pointer
  • 5.
    Effective Modern C++Study C++ Korea5 latomic 연산을 하고싶으면 weak_ptr로 체크후 객체를 point로 액세스 해야합니다.. l1) std::shared_ptr<Widget> spw1 = wpw.lock(); lauto spw2 = wpw.lock(); l//// if wpw's expired, is null l2)std::shared_ptr<Widget> spw3(wpw); l////if wpw's expired throw std::bad_weak_ptr 5
  • 6.
    Effective Modern C++Study C++ Korea6 l shard_ptr 순환참조 문제 .. 6 lb의 참조방식이.. 3가지 경우.. lraw pointer : A가 파괴됬을떄 B는 A가 dangle 포인터 인지 감지 불가능하고 참조했을경우.정의되지 않은 행동을 함.. lshared_ptr : a는 b참조 b는 a참조 l이 디자인은 a,b 모두 파괴를 방지하여 누수가 일어 남 lA std::weak_ptr 은 저 두 문제를 피하기 가능. la,b는 서로 가르키지만 b의 포인터의 참조는 영향을 안줌
  • 7.
    Effective Modern C++Study C++ Korea77
  • 9.
    Effective Modern C++Study C++ Korea9 template<typename T, typename... Ts> std::unique_ptr<T> make_unique(Ts&&... params) { return std::unique_ptr<T>(new T(std::forward<Ts>(params)...)); }
  • 10.
    Effective Modern C++Study C++ Korea10 template <class T, class... Args> unique_ptr<T> make_unique(Args&&... args); template <class T> unique_ptr<T> make_unique(size_t n); template <class T, class... Args> unspecified make_unique(Args&&...) = delete;
  • 11.
    Effective Modern C++Study C++ Korea11 auto upw1(std::make_unique<Widget>()); // with make func std::unique_ptr<Widget> upw2(new Widget); // without make func auto spw1(std::make_shared<Widget>()); // with make func std::shared_ptr<Widget> spw2(new Widget); // without make func
  • 12.
    Effective Modern C++Study C++ Korea12 processWidget(std::make_shared<Widget>(), // no potential computePriority()); // resource leak
  • 13.
    Effective Modern C++Study C++ Korea13
  • 14.
    Effective Modern C++Study C++ Korea14 std::unique_ptr<Widget, decltype(widgetDeleter)> upw(new Widget, widgetDeleter); std::shared_ptr<Widget> spw(new Widget, widgetDeleter);
  • 15.
    Effective Modern C++Study C++ Korea15 // create std::initializer_list auto initList = { 10, 20 }; // create std::vector using std::initializer_list ctor auto spv = std::make_shared<std::vector<int>>(initList);
  • 16.
    Effective Modern C++Study C++ Korea16
  • 17.
    Effective Modern C++Study C++ Korea17
  • 18.
    Effective Modern C++Study C++ Korea18 class ReallyBigType { … }; // as before std::shared_ptr<ReallyBigType> pBigObj(new ReallyBigType); // create very large // object via new
  • 19.
    Effective Modern C++Study C++ Korea19 std::shared_ptr<Widget> spw(new Widget, cusDel); processWidget(spw, computePriority()); // correct, but not // optimal; see below processWidget(std::move(spw), // both efficient and computePriority()); // exception safe
  • 20.
    Effective Modern C++Study C++ Korea20
  • 21.
    이 자료는 개념을설명하기 위해 책 내용 이외에 더 많은 내용을 조사해 포함 하였으며, 오류가 있을 수 있음을 미리 알립니다. 오류 : fb.com/bighilljae, hanjae.jea@gmail.com
  • 22.
  • 23.
    Effective Modern C++Study C++ Korea Identity Ex) int a; identity X Live long
  • 24.
    Effective Modern C++Study C++ Korea24
  • 25.
  • 26.
    Effective Modern C++Study C++ Korea 생성자에서 데이터를 가져올 parameter가 std::string이다. parameter를 받으면서 복사 연산이 수행된다.
  • 27.
    Effective Modern C++Study C++ Korea27 Text값을 변경 하지 않으니 const를 붙여주자. @EC++ cons : std::string 객체를 복사하는 비용이 크게 발생함.
  • 28.
    Effective Modern C++Study C++ Korea28 Text 는 value에 move 되지 않고 copy 된다. Text가 const string인 관계로 cast 결과는 rvalue const string
  • 29.
    Effective Modern C++Study C++ Korea29 1. std::move(text)가 rvalue const string이었다. 2. Constness를 유지하기 위해 copy constructor 로 동작함. 3. Const string을 non-const rvalue-reference에 넣을 수 없다.
  • 30.
  • 31.
    Effective Modern C++Study C++ Korea31
  • 32.
    Effective Modern C++Study C++ Korea32 • 기대했던 동작은 lvalue, rvalue 맞추어 서 process 실행 • 하지만 param이 function parameter 라 서 lvalue이다. • Param이 rvalue가 되도록 하는 동작이 필요하다. • 핵심은 move, forward가 cast를 무조건, 조건적으로 한다는 것 • Forward만 써도 되지 않나요? 예, 사실 그래도 되는데, 장점이 있습니다. Forward는 매번 타입이 필요하지만 move는 그렇지 않아요.
  • 33.
    Effective Modern C++Study C++ Korea33 감사합니다