This is something that seems like it might be answered in the C++ FAQ lite. I know two ways to go about something, but I don't know which one should be preferred.
I have a function that calculates the cross product from two vectors. So I pass it two "vectors", just arrays of doubles, and it does a bit of math, then needs to return 3 doubles, which I return in an array. But I have two options here:
(a) I could allocate the memory wherever I call it from, then pass that pointer to the function and have it just change the values from within the function, or
(b) I could allocate the memory in the function, and return the pointer to the allocated memory.
I like (b) because everything is contained within the function, but I'm not sure it's right. Is one better practice?
Also, another similar question: I want to pass it 2 "vectors". Because there are 3 coordinates for each vector in 3-space, that amounts to six values. I could just pass it x0,y0,z0,x1,etc, but that's a little annoying. Right now I'm allocating two 3-arrays of doubles, and passing them to the function. Then I use the values in the function, and delete the arrays from within the function when I'm done. Is that good or is it a bad idea?
It ultimately depends on the situation. But I would prefer option 1 if possible. That is because I then have the choice to get memory from the free-store or just use the stack (much preferred). Also I could then use a reference rather than a pointer.
1 2 3 4 5
void dot_prod(const matrix& a, const matrix& b, matrix& r);
// ...
matrix result;
dot_prod(m1, m2, result); // no need to use new or delete
Also, another similar question: I want to pass it 2 "vectors". Because there are 3 coordinates for each vector in 3-space, that amounts to six values. I could just pass it x0,y0,z0,x1,etc, but that's a little annoying. Right now I'm allocating two 3-arrays of doubles, and passing them to the function. Then I use the values in the function, and delete the arrays from within the function when I'm done. Is that good or is it a bad idea?
I personally would avoid that. Again you then loose the option of passing in auto variables to your function. Also I think it makes good sense to keep pure math separate from memory management.
It sounds like if you were to create a class/struct that has three members in it -- x, y, and z, that most
of your question(s) become much easier to answer.