Let’s say I have a structure named vertex with a method that adds two vertices:
struct vertex {
float x, y, z;
// constructs the vertex with initial values
vertex(float ix, float iy, float iz);
// returns the value c = this + b
vertex operator+(vertex b);
};
vertex::vertex(float ix, float iy, float iz){
this->x = ix; this->y = iy; this->z = iz;
}
vertex vertex::operator+(vertex b){
vertex c;
c.x = this->x + b.x;
c.y = this->y + b.y;
c.z = this->z + b.z;
return c;
}
In another calling function I want to add two vertices together and add the result to a vector<vertex*>. When is it safe to use the returned value to add to the given vector? If never, how would I implement it?
For example,
vector<vertex*> v;
vertex a(1, 2, 3);
vertex b(4, 5, 6);
v.push_back(&(a + b));
This is not safe, since you are storing a pointer to an automatic or temporary variable, which will be reclaimed when the current function terminates.
Mixing dynamically allocated objects with automatically-allocated ones is a serious risk. Sometimes the best strategy is to completely disallow automatic allocation (e.g., by making the constructor private and using a factory method to create new instance). You would then be responsible for eliminating these at some point.
A second option (not necessarily what you want) is to do everything by value. Have a vector of Vertex rather than Vertex*, and just have the vertices copied when they are stored. The way your class is written, all the fields are primitives, so this might be good enough and you wouldn’t run into performance or deep-copy semantic problems.