'should I check pointers in such situations?
I'm new to programming and game development in general every time I read and hear that pointers are a nightmare I want to ask if it is necessary to check pointers in such cases as shown below?
// create a component of a certain type and return a pointer to data of this type
StaticMeshCompt = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("StaticMesh"));
if (StaticMeshCompt)
{
// further work with the component
}
Solution 1:[1]
No, there's no need to check the pointer. The cases where CreateDefaultSubobject could return nullptr are :
- The class passed is
nullptr(It's guaranteed to be valid for anyUObject). - The class has the abstract flag (Not the case for
UStaticMeshComponent). - Allocation itself fails due to lack of free memory (At that point, you've got other problems).
Solution 2:[2]
As David G and ChrisMM said, it is necessary to check the pointer if the CreateDefaultSubobject function has a possibility of failing or returning a null pointer. If the function is known to always return a valid object, checking may not be necessary in that case.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | brobers |
