It makes no sense to return a link to a local variable. If you resort to the second solution (return the link to the vector new 'd), then there will almost certainly be a memory leak. By convention, getting a link usually means that some other object already controls the lifetime of the returned object.
There are many things you can do to get around this problem.
Do not perform dynamic memory allocation; change the function signature.
// Return a copy of the vector. vector<T> allOperations(T*** const &x, T*** const &y, T*** &z, int height, int width, int depth) { vector<T> results(height*width*depth); // ... return results; }
If you compiler runs copy elision and / or supports C ++ 11 moving constructors , a "copy" will never take place, and the return will be very efficient.
If you really want to dynamically allocate a vector to satisfy some other constraint, you also need to change the function signature:
// Return a pointer to a newly allocated vector. const vector<T>* allOperations(T*** const &x, T*** const &y, T*** &z, int height, int width, int depth) { vector<T>* results(height*width*depth) = new vector<T>; // ... return results; }
If you do, consider returning a smart pointer instead of returning a null pointer.
If it is a member function, perhaps you can save the vector inside the object.
template<typename T> class SomeClass { std::vector<T> results; public:
Another possible but very discouraged solution is to return a link to some global variable.
std::vector<T> results; // Modify global and return reference to global variable. const vector<T>& allOperations(T*** const &x, T*** const &y, T*** &z, int height, int width, int depth) { results.resize(height*width*depth); // ... return results; }
Or in its disguised (but exactly equivalent) form:
// Modify global and return reference to global variable. const vector<T>& allOperations(T*** const &x, T*** const &y, T*** &z, int height, int width, int depth) { // Global variable with name not visible outside the function. static std::vector<T> results; results.resize(height*width*depth); // ... return results; }