Object Storage? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Object Storage?

How am I able to do this? Shouldn't there be some kind of error? https://code.sololearn.com/cpY6h4O83q6q/?ref=app

4th Jul 2019, 6:15 AM
Daniel Cooper
2 Answers
0
The result of that code is actually an undefined behavior. The result is uncertain. It sometimes depends on the compiler you use. You can refer to http://www.cplusplus.com/reference/vector/vector/operator[]/ Edit: you have to copy the link and open it in your browser since the '[' and ']' characters is not count as something valid
4th Jul 2019, 6:58 AM
Agent_I
Agent_I - avatar
0
So as Agent_I said, this is undefined behavior according to the standard, but I wanted to extend their answer and throw in why this code doesn't crash. I'm not 100% sure this is accurate as I've never seen the source code for sololearn's compiler, but I'm confident it's pretty close. Member functions in classes can be thought of as functions with a hidden extra parameter. This code: obj_vect [1]->test_function(); Looks to the compiler like this: test_class::test_function(obj_vect[1]); obj_vect[1] is (hopefully) a null pointer, so if you had tried to access any data members, you'd be trying to read from nothing. test_class::test_function(0) Try adding an int to the class and assigning a value to it in test_function, that should cause it to crash as expected. This kind of problem can be difficult to debug, I'd suggest using shared_ptr and unique_ptr from the standard library if you're dealing with pointers. You can also test if an object is valid like so: if (obj_vect[1]) { //Object is valid }
26th Jul 2019, 6:11 PM
Nemo