Thursday, July 2, 2015

크로미움 스마트포인터



    코드리뷰를 받았다.  리뷰코멘트는, 

    To imply type-safe pointer ownership transfer to the caller, make this a scoped_ptr<base::DictionaryValue> then return changed_properties.Pass() from this function.

    type-safe한 포인터 오너쉽 전달을 하기위해 scoped_ptr을 리턴하여라.
    scoped_ptr을 쓰지않으면 type-safe하지않는다는건가?


    답은 chromium.org에 Smart Pointer Guideline에 있었다. (See: https://www.chromium.org/developers/smart-pointer-guidelines)

    What are the calling conventions involving different kinds of pointers?

    - 함수가 scoped_ptr로 된 변수를 전달받는다는 것은 그 변수의 소유권을 갖는다는 것이다.  같은 의미로, 호출하는 쪽에서는 Pass()를 이용해서 소유권을 완전히 넘긴다는것을 의미한다. temp한 변수의 경우 Pass()를 안써도된다.

    // Foo() takes ownership of |bar|. void Foo(scoped_ptr<Bar> bar); ... scoped_ptr<Bar> bar_ptr(new Bar()); Foo(bar_ptr.Pass()); // Pass() makes |bar_ptr| NULL. Foo(scoped_ptr<Bar>(new Bar())); // No need to use Pass() on temporaries.

    - 함수가 scoped_ptr로 리턴을 한다는 것은 호출하는 쪽에서 리턴되는 object의 소유권을 갖는다는 것이다. Pass()의 용도가 위의 예제와 비슷하다.

    // Foo takes ownership of |bar|, and the caller takes ownership of the returned // object. scoped_ptr<Bar> Foo(scoped_ptr<Bar> bar) { if (cond) { return bar.Pass(); // Transfers ownership of |bar| back to // the caller. } return scoped_ptr<Bar>(new Bar())); // No Pass() necessary on temporaries. // Note that on this codepath, |bar| gets deleted here. }

    - 함수가 raw pointer를 받거나 리턴한다는 것은, 소유권을 받거나 전달되지않았다(혹은 전달되었을수도)는 것이다.


    결론: Ownership을 갖기위해 Smart Pointer를 쓰자. Ownership이란? 해당 object를 변경할수 있는 상태? raw pointer를 쓰면 당연히 이게 위험하겠지..

    No comments:

    Post a Comment