Akamai Interview Question
SDE-2sCountry: India
Interview Type: Phone Interview
your answer seems good only thing is if you are taking reference or pointers then any change made might impact the original so a const reference or a const pointer would be better and the usage of these three, i.e., reference, pointer, and object (pass by value) depends on the context of what is required.
If vector is needed to share among other class objects or outside your code block, reference option is gone.
use of objects in vector require copies created. This is more portable and simple but if objects are heavy in size or resouces, this option is gone too.
Pointers require dynamic allocation of your objects and deletion of them at some point where the usage is completed. This requires some programming discipline which is difficult to ask for. Smart pointers in the vector may give a solution to your need if usage of new is not threatening to your principles/standards.
Yep, you can not create a container of references. Also, vectors have the resize problem, so if the vector runs out of its initial memory, a new vector is made in the memory elsewhere which 'copies' the objects in a vector. This might cause problems with a vector of pointers. The answer depends on the context but these are few pointers to remember.
My order of preference
- LinhHA05 July 23, 2013Performance
* Reference
* Pointer
* Object
Maintability/Debug
* Reference
* Object
* Pointer
Reason:
- Performance: Reference and Pointer are equaly well since it introduce no overhead, object might require copy which is very expensive if the size of the object is large. Reference is better then pointer since it require no extra test to see the refered object exist.
- Maintainability: it is generally well-know that raw pointer cause more trouble so people prefer to use smart pointer, you have to be very careful to use the raw pointer to make sure the refered object is valid and clean up the memory after all. Reference can be used anywhere object can be used.
@As mentioned in the below comment. It would be better to use const reference (const object and pointer) if you don't want to change the value of refered objects, it also help compiler to produce more optimized code