Is there any advantage to using a reference argument in this function?

I have defined the following class:

class Action
{
    public: 
    Action(){ _bAllDone = false; }

    void AddMove( Move & m );
    private:
        std::deque<Move> _todo;
        bool _bAllDone;
};

      

The AddMove element is defined as follows:

void Action::AddMove( Move & m )
{ 
    _todo.push_back( m ); 
}

      

I noticed that without the reference argument to this function, the Copy Constructor instance was called twice, since with the reference argument it was called only once. Is calling Copy Constructor only once and not twice a reason to use a reference argument?

+2


source to share


3 answers


The deque class in STL must maintain a copy of the element you are passing to the push_back method. This is where one constructor comes in.

If you get rid of the reference in addMove (), you first get a copy of the parameter (and therefore one call to the copy constructor), and then when you push back, you get a second copy.



Calling the copy constructor twice is wasteful, so reference is preferred. However, you must declare the addMove () parameter as a const reference to indicate to the caller that the element will not be modified. With this confidence (provided you don't break it), it is safe to pass an object by reference without the hassle and without paying a penalty for copying the object.

+17


source


It seems like a big advantage to me. Things can get really slow if you do a lot of additions iteratively. The actual amount of work will depend on the definition of Move and its copy constructor. And small changes can have serious performance implications. To bite anyway while walking past the copy will still double the work.



The overall effect of this will depend on how much of the entire processing is spent on this operation. Do it once, you will never notice; do this a few thousand times and it can be significant. However, as a general principle, avoid copying data where you can confidently reference it, especially since there isn't much clarity or complexity in that case - it's as easy to do it quickly as it should make it slow, so why don't you make it slow?

+4


source


It must be a reference, otherwise you will be carrying an unnecessary (and potentially incorrect) copy of the argument. It should also be const

, otherwise you will unnecessarily limit your subscribers.

Note that names with leading underscores are reserved for the language implementation, so your program is "undefined".

NTN

0


source







All Articles