Smart pointers in C ++ API?

Quite often, it is suggested not to use the source pointers in modern C ++, with the exception of a few rare cases. What is the common practice of using smart pointers in the C ++ library APIs?

The following use cases come to my mind:

  • A function that returns a new object.
  • A function that returns a new object, but also created another reference to this object.
  • A function that uses only the object that receives as an argument.
  • A function that takes ownership of an object.
  • A function that will store a link to the object that it received as an argument, but there may be other links to the same object (from the callers).
+5
source share
3 answers

Unfortunately, the design of the library’s API goes far beyond the language itself: all of a sudden you have to take care of implementation details such as ABI .

C, , ++ ABI (Microsoft ABI V++ Itanium ABI, gcc Clang), ++ , , libstd++ ( gcc), , libstd++ , ​​ lib++ ( Clang), std::.

, , , ​​ , , . ++, , C, ( ).


, ++ API:

1) , .

, ; , std::unique_ptr<Object>.

2) , , .

. , , - . , std::shared_ptr<Object>.

3) , , .

, , , .

  • , (const )
  • , ,

4) , .

: std::unique_ptr<Object>.

5) , , , ( ).

: std::shared_ptr<Object>

+13
  • .

    std::unique_ptr<Foo> func();
    

    auto .

    auto u = func();
    

    , :

    std::shared_ptr<Foo> s{func()};
    

    , , , :

    Foo func();
    
  • .

    std::shared_ptr<Foo> func();
    
  • , "" .

    void func(Foo& obj);
    void func(const Foo& obj);
    

    , , nullptr.

    void func(Foo *obj);
    void func(const Foo *obj);
    
  • .

    void func(std::unique_ptr<Foo> obj);
    
  • .

    void func(const std::shared_ptr<Foo>& obj);
    

    ( ) , .

+6

, .

, , , .

. , API.

- RAII/, ( ) .

0

Source: https://habr.com/ru/post/1534199/


All Articles