I have an vector, filled with objects:
std::vector<MyClass> vec;
vec.push_back(MyClass("Hi", 10)); //example, could be any class
Later, when it is filled, I want to access it:
for(unsigned int i = 0; i < vec.size(); i++)
{
MyClass *c = & vec.at(i); // <--- HERE
if(c) // <--- AND HERE
{
c->memberOfMyClass = x;
}
}
Is using c more dangerous than using vec.at(i) directly? Do I need the protection with if(c)? Can c be nullptr? I guess no, because the vector does take object, not pointer to objects.
Is using c more dangerous than using vec.at(i) directly?
Not in the example. It is unnecessarily complex however.
Can c be nullptr?
Not in the example.
Do I need the protection with if(c)?
No; see above.
Is using a pointer to an elements in an vector dangerous?
Using pointer - or any other form of indirection - in general can be "dangerous" in the sense that the lifetimes of the pointer and the pointed object are separate. Therefore you must be aware of what the lifetime of the pointed object is because if it is shorter than the pointer, then pointer will be left "dangling". Assuming the lifetime wrongly can lead to undefined behaviour.
An example of a broken program:
std::vector<MyClass> vec{
{"Hi", 10},
};
MyClass *c = &vec.at(0); // OK
vec.emplace_back("Hi again", 42); // c may be invalid now
c->memberOfMyClass = x; // potential undefined behaviour
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With