Passing containers by value or by reference

I am aware of the differences between passing by value, reference or pointer in the general case. However, my question is about the special case of a container with a simple structure.

Assuming this case:

class image{ image()=default; image(image const&)=default; ~image()=default; int w; int h; uchar* data; } 

When transferring an object of this class, only two integers are copied, and the pointer is not all data. In this case, is there a purpose to pass it by reference? Or is there a goal not to pass it by reference?

What caused this question is that I read that iterators in C ++ were designed to be light and passed by value. Therefore, I believe that this concept can be applied to classes, which are a container for actual data, not data.

+6
source share
2 answers

Imho, the best recommendations on how to pass arguments can be found in Herb Sutters' excellent conversation. Back to basics! Fundamentals of the modern style of C ++ . In your particular case, a transition by value will be the best option, since your structure will be cheap to copy.

Cpp parameter passing overview .

+6
source

With the default copy constructor, any copy will be shallow and will not make a copy of the memory pointed to by data . Therefore, when you pass by reference, only two integers and a pointer will be transferred, for a total of approximately 12 bytes (depending on your architecture, i.e. the size of the pointer).

This difference is so small that it really doesn't matter whether you pass it by value or by reference. The latter can be a little faster, because the pointer can probably always be passed through the CPU register, and 12 bytes cannot, but this is really micro-optimization.

Personally, I pass anything other than primitive types to the default ( const ) link if I have no reason not to see it (see jupp0r answer ). The main advantage during development is that as the class grows, I donโ€™t have to worry about when it gets too big and changes all my functions to follow the link.

As for the default iterators, C ++ by default: note that they are mainly for pointers. In fact, I know that to compile Microsoft Visual C ++ in release mode with optimizations turned on, iterators for adjacent data structures like std::vector will be reduced to this. I do not know if other compilers can do this, I would think so. However, you will notice that if you turn off optimization, then suddenly there is a difference between writing it++ and ++it in loops, for example, only because of the additional copy operation in the first case. Therefore, even a โ€œcheap copyโ€ can make an impact if you do it often enough. As usual: when you are worried about performance, measure and decide based on numbers.

+5
source

All Articles