3 ms·
Because we might need add_numbers() to be able to work with reference-counted data. Obviously this program by itself is useless, but these functions could be a
by codedokode 4y ago
Because we might need add_numbers() to be able to work with reference-counted data. Obviously this program by itself is useless, but these functions could be a part of a larger program.
- LaLaLand122 4y agoNo, we don't. add_numbers() doesn't need ownership of the data, so you would never give it ownership of the data. If you happen to have the data in a reference-counted type you would get the data from it (https://en.cppreference.com/w/cpp/memry/unique_ptr/get https://en.cppreference.com/w/cpp/memry/unique_ptr/get / https://en.cppreference.com/w/cpp/memory/shared_ptr/get https://en.cppreference.com/w/cpp/memory/shared_ptr/get), and pass it to add_numbers(). The data would still be guaranteed to exist because the caller of add_numbers() is going to hold a reference at least until add_numbers() returns.
- jeffbee 4y agoSure, but if you need it to work with actual reference-counted pointers from external callers, how could it be simpler? The Rust version doesn't have that ability. The best we could expect from this example is for the C++ compiler to deduce that the shared_ptr is irrelevant because the callee has internal linkage.
- codedokode 4y agoAs I understand, one cannot convert shared_ptr to unique_ptr, so if we declare an argument to add_two_numbers() as unique_ptr, then we won't be able to pass a shared_ptr to it.