I am a new C++ developer, and am taking a software engineering class at my university, and the project must be written in C++17, and able to be compiled with MSVC++ 19.
I have had several years of experience with Java and (less so with) C, but the transition to C++ has been... difficult, to say the least, and the comparatively large number of 'pointer'/reference types in C++ has been the crux of the matter.
Long story short, which of these 'pointer'/'reference' types should I be using in my function/method/constructor parameters, return types, and object declarations, and why? My goal is to ensure memory robustness while minimising manual management—similar to Java.
C
In C, things are straightforward: everything is pass-by-value, and there are two types: primitives, and pointers to primitives:
int a = 5; // A is a primitive int
int *ptr = &a; // *ptr dereferences to a, while itself containing the address of a, which the & prefix operator exposes
Given C's pass-by-value paradigm, if one wants to manipulate a variable within a function, a pointer is passed as the argument, and the pointer is then dereferenced within the scope of the function. For memory that needs to be available on the heap, we have malloc/calloc/realloc
, and free
. The rule is simple here: memory that is malloc
ed to, but not free
d by the end of program execution, constitutes a memory leak.
Java
Java makes things even easier, and we have two types, primitives and objects, which are always references:
int a = 5; // primitive int
ArrayList<String> myList = new ArrayList<String>(); // note 'new' keyword; myList's members/methods can be accessed directly with the dot operator such as myList.add("hello")
Memory management is straightforward—albeit slower than C/C++—as objects that go out of scope are automatically cleaned up by the Java garbage collector. No need to worry about delete
ing any new
objects.
C++
Now, I know for a fact that C++ inherits the &
prefix operator as well as the *
dereference operator from C. However, there are also the following 'pointer' types:
- the
&
post-fix operator:std::string&
- the set of 'smart pointers':
std::auto_ptr
(apparently deprecated)std::unique_ptr
std::shared_ptr
std::weak_ptr
Now, I have seen the following argument types for static/instance functions and constructors (object
is a placeholder here; replace with something like string
or vector
):
std::object obj
std::object& obj
std::object&& obj
const std::object obj
const std::object& obj
- the 'smart pointer' types mentioned above
Some of these pointer types are associated with the function (apparently not a function, and doesn't move anything) std::move
, but I can't figure out a pattern, based on the C++ code I've seen here and elsewhere on the Web.
I have also seen the term 'copy constructor' and 'destructor', and it has been difficult trying to understand all of these terms and what they do, or how they look like (don't get me started on C++ syntax, which is... painful).