C++ from Basics to Mastery — Part 7
Differences between const, reference, and pointer
The articles written on this blog were created with the goal of teaching. Also, the information in the article may be incorrect, so please be careful.
When passing an object to a function, you must decide whether to use a value, reference, or pointer. Although they are similar on the surface, there is a big difference in the possibility of copying and modifying them.
Values and References
void PrintItem(Item item); //Passing by value
void UpgradeItem(Item& item); //passing by reference
void PrintItem(const Item& item); //Passing constant references
If you pass it by value, the function can receive a separate copy. If it's a small int, there's no problem, but if it's a string and an object with multiple members, copying may be unnecessary.
Item&is an alias for the original. If you modify it within the function, the original is also modified. const Item&Avoids copying and prevents modification of the original. This form is often used when passing an object that is to be read only.
class Monster
{
public:
int GetHealth() const
{
return health;
}
const std::string& GetName() const
{
return name;
}
private:
int health = 100;
std::string name = "Slime";
};
The const after the function means that this member function does not change the state of the object. const MonsterThis is where there is a difference between functions that can be called and functions that cannot be called.
stringconst std::string&You can avoid copying the string by returning . However, it is important to remember that it becomes dangerous if the original object is destroyed before the returned reference.
pointer
A pointer stores the address of an object.
Monster monster;
Monster* target = &monster;
if (target != nullptr)
{
std::cout << target->GetHealth() << '\n';
}
A normal object is.and the object pointed to by the pointer is->approach. A pointer may not point to anythingnullptrInspection is needed.
The important point here is that just because a pointer points to an object does not necessarily mean it owns that object. Raw pointers, where it is not determined who will destroy the object, become more dangerous as the code grows.
Monster* target = nullptr;
{
Monster monster;
target = &monster;
}
//target holds the address of a monster that has already been destroyed.
This type of pointer is called a dangling pointer. Even if the address itself remains, the object at that address has already reached the end of its life.
References are good to use in situations where they must point to a valid object. Pointers are suitable for situations where the object may not be present or may point to another object.
And if the pointer must own the object, it is better to consider smart pointers before raw pointers.