I want to ask one simple question which is making me confuse.
for example if I write in argument there is no reference &. but in the second case I have used & with rectangleType&, I am having confusion why we use this & when we can do it without this &. Where is this necessary and why we use it. My question is not about copy constructor.
rectangleType rectangleType::operator+
(const rectangleType rectangle)
Case 2:
rectangleType rectangleType::operator+
(const rectangleType& rectangle)
When you pass an object like rectangleType (or any other type) by value, you're making a copy of that object. This means:
Any changes made to the object by the function are not seen by the caller, since the changes are made on a copy, not the original object.
The act of copying the object incurs a performance cost.
Copying the object may not even be possible for some types.
So, pass by reference whenever:
You want the function to be able to modify the original object.
You want the code to run faster by not having to make a copy.
The object you're passing doesn't have a public copy constructor.
Pass by const reference whenever you don't need the function to be able to modify the original object.
For user-defined types, this essentially boils down to "pass by reference wherever possible."
How can you state that your question is not about copy construction if the answere is about it?
With a const reference no copy is made, this can be crucial for very large objects
There are classes wich explicitely dont provide a copy constructor, this way you can still pass them around.
So to conclude: You get benefits without disadvantages.
In the first method, it will receive a (complete) instance of rectangleType, that will be created using the copy constructor just to be passed as a parameter.
In the second method, it will receive a reference to an already existing instance; no copy will be made.
Related
From what I understand: when you pass by value, the function makes a local copy of the passed argument and uses that; when the function ends, it goes out of scope. When you pass by const reference, the function uses a reference to the passed argument that can't be modified. I don't understand, however, why one would choose one over the other, except in a situation where an argument needs to be modified and returned. If you had a void function where nothing is getting returned, why choose one over the other?
EDIT: So basically passing by const reference avoids copying the object. So in what situations is copying the object good? I mean, why not just use const references all the time if it optimizes performance all the time?
There are two main considerations. One is the expense of copying the passed object and the second is the assumptions that the compiler can make when the object is a a local object.
E.g. In the first form, in the body of f it cannot be assumed that a and b don't reference the same object; so the value of a must be re-read after any write to b, just in case. In the second form, a cannot be changed via a write to b, as it is local to the function, so these re-reads are unnecessary.
void f(const Obj& a, Obj& b)
{
// a and b could reference the same object
}
void f(Obj a, Obj& b)
{
// a is local, b cannot be a reference to a
}
E.g.: In the first example, the compiler may be able to assume that the value of a local object doesn't change when an unrelated call is made. Without information about h, the compiler may not know whether an object that that function has a reference to (via a reference parameter) isn't changed by h. For example, that object might be part of a global state which is modified by h.
void g(const Obj& a)
{
// ...
h(); // the value of a might change
// ...
}
void g(Obj a)
{
// ...
h(); // the value of a is unlikely to change
// ...
}
Unfortunately, this example isn't cast iron. It is possible to write a class that, say, adds a pointer to itself to a global state object in its constructor, so that even a local object of class type might be altered by a global function call. Despite this, there are still potentially more opportunities for valid optimizations for local objects as they can't be aliased directly by references passed in, or other pre-existing objects.
Passing a parameter by const reference should be chosen where the semantics of references are actually required, or as a performance improvement only if the cost of potential aliasing would be outweighed by the expense of copying the parameter.
Passing arguments by value and thus copying them can be expensive - const references avoid that expensive step while still promising the caller that the object won't be changed.
Usually fundamental types (int, double, ...) are passed by value, while class-types are passed by const reference.
There can however be exceptions where pass-by-value for class-types can be beneficial.
Making a copy of an object could greatly affect the performance in some cases. Consider a function which argument will be std::vector<long> and you want to pass vector with 1 million elements. In this case you'll want to use const reference over passing by value. In this SO question you could find simple general rule for your question.
Sometimes, making a copy of an object can be expensive and so pass-by-const-reference will avoid having to make that copy. Otherwise, I would say that you should simply pass-by-value if that is what is semantically required.
To avoid making an unnecessary copy, thus improving performance.
Passing an argument by value has the overhead of a copy of the object being passed to the function.
Maybe an object isn't copyable and your choices are limited.
Because of the performance benefits you will get. Lets say you have a big object (in terms of size in bytes). Now, if you pass this object by value to a function a unnecessary copy needs to be created of this, however you can get the same effect by passing a const reference to that object itself without creating copy. Since a reference is normally stored as a pointer under the hoods, the cost of passing a reference is just sizeof(pointer).
An array can't be passed by value, so this is a good time to use a const pointer.
I am new to C++ (coming from C#) and I want to get that memory stuff right from the beginning.
In the following snipped a variable of type WorldChunkCoordinates is passed by value to the inline constructor of WorldChunk and then the passed Coordinates are assigned to WorldChunk::Coordinates, which I believe is a copy operation as well.
(copy-assignment operation?)
If my assumptions are correct then this would be kinda stupid, because I copy the instance twice. I think it would be much more performant if I would pass by value and assign by reference pointer. But WorldChunk::Coordinates is not a pointer neither a reference.
WorldChunk(WorldChunkCoordinates Coordinates) {
WorldChunk::Coordinates = Coordinates;
}
Is there a way to safe my programm from copying the instance twice?
If so, how?
Also: Is assigning by = always a copy operation by default?
And: How should I know that a specific class may have another copy assignment operation that copies by reference?
Its a known and solved problem, called initializer list (not to be confused with the container). Looks like
WorldChunk(WorldChunkCoordinates Coordinates) : Coordinates(Coordinates){}
Consider using lower case letters for variable names.
You could also use
WorldChunk(const WorldChunkCoordinates &Coordinates) : Coordinates(Coordinates){}
but it is not obvious that dereferencing is faster than copying, especially when taking compiler optimizations into account.
first of all a simple solutuion:
change your method to:
WorldChunk(const WorldChunkCoordinates& Coordinates) { WorldChunk::Coordinates = Coordinates;}
This will lead to a single assignment instruction because coordinates is a reference.
The default constructed assignment operator assigns memberwise.
The parameter of the assignment operator is (usually) a const reference to the object so that you don't copy the parameter.
By the way a little tutorial: http://www.cplusplus.com/doc/tutorial/ which is very good in my point of view.
The convention in C++ for user type function arguments is to pass by const reference (const MyType&) for input arguments, and by reference for in-out arguments (MyType&).
I am a little confused about the differences between call by value and const call by reference. Could someone please explain this to me. For example, do they both protect against changing the callers argument, are they fast for all object sizes, do either copy the argument while one doesnt, and which use more memory when making a copy?
do they both protect against changing the callers argument
Passing by value creates a copy of the argument provided by the caller, so whatever the function does, it does it on a separate objects. This means the original object won't ever be touched, so in this case the answer is "Yes".
Passing by reference to const, on the other hand, lets the function refer the very same object that the caller provided, but it won't let that function modify it... Unless (as correctly remarked by Luchian Grigore in the comments) the function's implementer uses const_cast<> to cast away the const-ness from the reference, which is something that can be safely done only if it is known that the object bound to the reference was not declared to be of a const type (otherwise, you would get Undefined Behavior).
Since this does not seem to be the most likely scenario considering your question, and considering that in general accepting a reference to const represents a promise that the argument won't be touched, then the answer is that as long as we assume this promise to be fulfilled, passing by reference to const won't alter the argument provided by the caller. So the answer is "Yes" again - with the little caveat I mentioned above.
are they fast for all object sizes
No. Although you should first define "fast". If the type of the object being passed is expensive to copy (or to move, if a move is performed rather than a copy), then passing by value might be slow. Passing by reference will always cost you the same (the size of an address), no matter what is the type of the value you are passing.
Notice, that on some architecture and for some data types (like char) passing by value could be faster than passing by reference, while the opposite is generally true for large enough UDTs.
and which use more memory when making a copy?
Since only one of them is causing a copy, the question has an obvious answer.
The main difference is that passing by const reference (or non-const) doesn't make a copy of the argument. (the copy is actually subject to copy elision, but theoretically it's a copy that's passed to the function when you pass by value)
In some cases, passing by value is just as fast, or even faster (typically when the object is at most the size of a register). You'd usually pass basic types by value, and class-types by reference.
When passing by const reference you can still modify the original value just by casting the const away (via const_cast), but that results in undefined behavior if the original value is const.
call by value will copy all the elements of the object it does protect the callers argument because if you are going to change something it is only a copy you are changing.
calling by const reference does not copy elements but because of the "const" it will protect caller's argument.
You const reference.
I suppose that you mean the difference between:
void Fn1(MyType x);
and
void Fn2(const MyType& x);
In former case, a copy of the object is always created, which makes it slower especially if the type has a non-trivial constructor. The original object will be unaffected by any changes done on the copy within the function, but the copy itself can be changed.
The latter example will not create a copy and will in general be faster. Inside the function, only the const functions can be called on the argument (unless you resort to dirty tricks like casting away constness), thus guaranteeing that the object will not be modified.
IMPORTANT: This discussion doesn't cover types with special semantics, like smart pointers. In that case, call by value will still allow you to change what is logically the same object, i.e. not the smart ptr instance itself but the object it points to.
So here are the answers to your questions:
do they both protect against changing the callers argument: yes, the original object will remain unchanged (excluding tricks)
are they fast for all object sizes: they are not equally fast - call by reference is in general faster, except for some primitive types where speed is more or less the same or maybe even marginally faster, depending on compiler optimizations.
do either copy the argument while one doesnt: call by value creates a copy, call by reference doesn't
which use more memory when making a copy? call by reference doesn't create a copy so the answer is clear
One other point worth mentioning is that call-by-reference functions are converted into inline functions.
I have a class.
class Books
{
private:
int m_books;
public:
Books(int books=0)
{
m_books = books;
}
Books(const Books &source) //Here is what I don't understand.
{
m_books = source.m_books;
}
};
I can't understand why it has to be Books(const Books &source), and not Books(const Books source).
When you have
Books(const Books &source)
the source is passed by reference. When you have
Books(const Books source)
it would have been passed by value. But to pass by value you are the copy constructor. So to avoid an infinite recursion, the copy constructor must accept a reference.
Books(const Books &source)
means that a reference is passed, instead of the actual variable (as in pass-by-value, as in the case of primitives such as int or char).
In this case, since you are building a copy constructor, you don't want to make modification to the object whose reference is passed in, so the argument signature is prefixed with const (this guarantees that the argument being passed in is immutable)
(Note, mostly importantly: pass-by-value here would introduce infinite recursion - see #AProgrammer's answer) Aside from that, it also would be unnecessarily expensive to pass in source by value (meaning: make a copy of the entire source when the copy constructor is called), we just use a reference instead.
Additional reading you might be interested in: C++ Pass by Reference vs. Value
What you're looking at is called the copy constructor. The reason why you should pass an object by a reference is because if you pass it by a value then a copy of the object has to be constructed, so it would have to call the copy constructor again. And again. And again ...
So book is passed by reference instead of copied by value.
Using a reference means that there's no copy involved. If you had:
Books(const Books source)
Then the argument the caller passes would have to be copied to source. If you use a reference instead, no copy is made. This provides better performance. With small amounts of data it doesn't matter much, because it's a simple class with no large amount of data. But with more complex classes, copying can be expensive. Using references avoids that problem.
However, in the case of copy constructors, avoiding a copy is vital. Not for performance reasons, but by the fact that copying involves a copy constructor. When the copy constructor gets called, another copy would have to be made if a reference was not used. That means another call to a copy constructor. There, yet another copy would have to be made. Yet another call to a copy constructor.
As you can imagine, this would result in an infinite amount of copy constructor calls. By using a reference this situation is avoided.
Read about copy constructors: http://www.cplusplus.com/articles/y8hv0pDG/
It is passing in a reference to the Books source object. That it all.
I hope this helps.
Can some body tell me the reason why we usually put const and & with some object which is passed in the constructor for example.
Book::Book(const Date &date);
The confusion that i have here is that usually & sign is used in the some function because the value is passed by reference and whatever changes happen to that variable in the function should reflect afterwards. But on the other hand const says that no assignment can be done to that variable.
If some body have some good idea about that please let me know the reason for that.
This is done to avoid an unnecessary copy. Take, for example, the following code:
Book::Book(Date date):
date_(date)
{
}
When you call this constructor it will copy date twice, once when you call the constructor, and once when you copy it into your member variable.
If you do this:
Book::Book(const Date &date):
date_(date)
{
}
date is only copied once. It is essentially just an optimisation.
The most common alternative is to pass by value:
Book::Book(Date date);
Passing by const reference prevents the parameter date from being copied when the parameter you pass is already a Date. Copying objects can be unnecessary, can be costly to perform, or it could result in a sliced object (and the incorrect results).
'Slicing' is basically demotion of an object's type via copy to its base. For a polymorphic type, this can actually change its behavior because the parameter would be copied as its base (Date), and then calls to its polymorphic interfaces would be different because the implementation has changed (e.g. its virtual methods would use the base's implementation instead).
It means that you pass the object via refrence (as you noted), but the object itself cannot be changed from the function (ctor in this case).
The reason for this could be:
you do not want to copy the full object, to make your code more efficient
you do not want to accidentially change the passed-in object
you want to be able to use the function with unnamed temporaries
you want to be able to pass objects that derive from the noted type (Date in this case)
For the third point, consider:
Book b(Date());
It's typically a performance optimization for input parameters. If you omit the '&' the parameter is accepted by value and the input object will have to be copied before being passed to the function. Passing by reference bypasses the copy.
In c++, when you have a parameter type of a function be something like const Type&, what you are doing is allowing a user to pass some value in by reference - A pointer to the value is implicitly passed in, but for ease of use, the compiler allows you to treat it as if it was a value.
In some cases, the compiler can also optimize it so that no pointer is used at all, and the function can refer directly to the memory of the value.
The reason that const is used is to safeguard yourself from altering memory that the user doesn't expect you to alter, and also to have it still work if the user passes in a const variable.
A const reference is a way of passing the data to the class without copying the data to a local copy, and still guaranteeing that the original object won't be modified by the function.