C++ Reference vs Pointer best practices -


I have read several stack overflow answers about this and I am not very satisfied with the responses so that I want to collect them here .

When using the non-primitive and complex objects for parameters, it is generally advisable to pass them by reference when calling the function, there is no possibility of the parameter being used. This is mostly due to the fact that the references are guaranteed to assume value so that you do not know whether the parameter reference is taped or not.

When the return value of the function is a non-primitive and complex object you should usually withdraw a pointer because it is easy to confuse the function, which returns a return with that reference, which Gives a value when they look alike.

For example, take this class

  structure rectangle {int x, y; Integer width, height; Rectangle (int x_, int y_, int width_, int height_): x (x_), y (y_), width (width_), height (height_) {}}; Class image {public: image (): dimension (0, 0, 0, 0) {} ~ image (); Zero Setments (brace rating and new dimensions) // Reference is recommended near [amplitude = new dimension; } Rectangle GetDimensions () // is usually the best practice in this case to return by value {return dimension; } Private: rectangle dimension; };  

Is this the best practice for reference versus pointers in parameter and return types? If not, please explain why not.

Edit 1: Non-Dimensions () has been changed to return the value because it is believed that efficient

A reference is a reference and a value is a value. They have different words and saving the copy operation can only be a serious problem.

More specifically, theory references should be used only when the receiver cares about identity (and not only the value of the object) if the identity is not necessary and the name of the function / method is only the value If the person cares about, the value should be used instead.

If you are absolutely sure that you have a conference reference instead of a value to save copy operations on aliasing or lifelong issues Can decide to pass.

There is a detailed example in it (which, incidentally, is also talking about rectangles in the context of very fine which you can run contexts from then on When the values ​​should have been used instead, and also keep in mind that no help can be made to deal with aliasing and lifetime issues.


Comments

Popular posts from this blog

import - Python ImportError: No module named wmi -

Editing Python Class in Shell and SQLAlchemy -

lua - HowTo create a fuel bar -