I was interested in the question - when is it better to use links, and when are pointers as parameters of functions for objects?

For example:

CMyData1 data1; CMyData2 data2; func_r(data1, data2); func_p(&data1, &data2); 

In theory, it makes absolutely no difference, it’s a bit more comfortable with the links, because you don’t have to write -> , but use the native one for objects . .

Can you say that you can use this rule:

if the function expects only existing objects to enter, then references are used, if it is assumed that the object may not exist, then pointers need to be used (so that nullptr can be passed)?

    1 answer 1

    • function expects an existing object without transfer of ownership - is used by T &
    • function expects an existing object without transfer of ownership or nothing — optional<T &>
    • the function expects an existing object c transfer of ownership or nothing - using smart_pointer<T>
    • the function expects a piece of the array (string) - using array_view<T> or string_view<T>

    Thus, the use of raw pointers is limited to the implementations of these optional , smart_pointer , array_view , etc.

    • A smart pointer is not necessarily a transfer of ownership, maybe division is shared_ptr , or just an attempt to do this is weak_ptr . - αλεχολυτ
    • Thanks, in my time, there was no optional :) - in theory, this immediately solves the question of the possibility of transferring an empty object, but what does it mean to “transfer ownership”? - Zhihar 1:08 pm
    • The @Zhihar type pointer std::unique_ptr is owning, that is, when deleting (for example, calling the destructor), it also deletes the object that is attached to this pointer. This is the basic concept of smart pointers. - αλεχολυτ