in Java, a link is a "smart pointer" collected by garbage.
C ++ also uses the concept of smart pointers, which are in the <memory> library called unique_ptr and shared_ptr . shared_ptr is reference counting, so it can be used in the same way as Java references. unique_ptr is similar, except that it is not copyable and a bit lighter. The advantage of both will never be to use the delete keyword and be able to rely on “pointers” that are protected by exceptions.
C ++ also supports the concept of reference, which is usually a good choice for passing objects around (and even better, reference-to- const ). Links in C ++ are tied to the type of object being passed, so you need to specify (using the & symbol) in the function signature
#include <string> void foo(std::string& bar) { bar = "world"; } void foo2(const std::string& bar) { //passed by reference, but not modifyable. } int main() { std::string str = "hello"; foo(str); foo2(str); }
As for raw pointers, you can almost always avoid them using either a smart pointer, a link, an iterator, or a missing parameter. simple regular pointers come with a mixed-up "gotchas" package that C ++ inherited from C - if you have a fairly recent compiler, you never have to really use them at all (unless you are going to do things like reinvent the wheel for learning with memory management, data structures, etc.)
source share