Use the same variable as input / output in a function

advertisements

I'm writing a Qt GUI program in conjuction with OpenCV to create a people tracking application. OpenCV has a lot of functions that take a matrix as input and output, for example a color conversion one:

cvtColor(inputArray src, outputArray dst, int code, int dstCn=0);

Mat is the default matrix class of OpenCV, and assuming I have a Mat object called frame, I would implement the function like this to change its properties:

cvtColor(frame, frame, CV_RGB2HSV,0);

Is there any downside on using the same variable as input and output on any function? or should I create a copy first?

or should I look in every function documentation?


I think it's a personal choice. Here's some personal samples:

Take readonly input, a reference to the output and, after you process the input, push it to the output. Optional error result friendly.

bool function(const type& input, type& output){
    output = input;
    return true;
}

Take readonly input, assign it to output, change output and return it (C++11 move optimized).

type function(const type& input){
    type output = input;
    return output;
}
type output = function(input);

Here you force a new copy of the object as the argument and you can use it and return it (C++11 best when you don't want to alter your copy). See also: Want speed, pass by value..

type function(type input){
    // modify input
    return input;
}
type output = function(input);

  1. Input and output in the same argument. Use with caution. Can return error.

    bool function(type& put){ return true; }

It depends on your design. Don't need errors?... use a movable one. Need errors?... use one that leaves the return value accessible to you. Or, just follow existing practices but know how each can help or penalize your performance like:

// this makes a pointless copy for the input (use const ref here)
bool function(type input, type& output){
    output = input;
    return true;
}

(Right way is)

bool function(const type& input, type& output){
    output = input;
    return true;
}

PS: Personal opinion of a self taught C++ dev :)