Hey guys , so I was trying to send a vector to a function to read it only " const " and I thought I should send a pointer or reference for better performance , but
when I took the size of the reference it was the same size as the vector ? I thought sending it will just send the size of the first element ?
When you use sizeof on a reference it will return the size of the object that the reference refers to. That is one of the main advantages with references, i.e. that you can use them as if they where the original object without having to dereference like you have with pointers.
?? Functions do not have elements, and you cannot have references to them. If you meant a reference to a vector, no, it sends the size of the vector (not the number of elements in it).
I meant the vector , for example if I took the vector's size and it was 24 bytes , and I made a reference or pointer to it so I can send it to a function , sending a reference is good when you have a big object and you want to send it to a function " for a better performance "
and by elements I mean the size of a first element , for example an int would be 4 bytes on some systems.
A reference in C++ can be thought of as just another name for the same object. Thus, taking the size of a reference is equivalent to taking the size of the original object it refers to; so if you call sizeof() on the original object and the reference, you will get the same result (24 bytes, in your example). Similarly, assuming no other changes were made, a call to the length() method would also return the same value, and so on.
@keskiverto , so it will send the memory location to the function instead of copying the whole object ? and what's the size of the memory location usually ? isn't in case of an array or vecotr should be the size of the first element which is 4bytes on most system if it was an int ?
The sizeof() operator works strangely on arrays (returning the size of a pointer to the first element) because in some cases the array may silently decay to a pointer (such as when passed as a argument to a function). This does not happen with vectors as they are a class and do not have that "decay to pointer" behavior.
I suppose you could think of the reference as sending the memory location of the original vector, but that is closer to what a pointer implementation would look like (though you could implement the reference semantics in that way, which is why what you are saying isn't necessarily wrong). That said, you have the right idea. But things like sizeof() will, as I mentioned, act as if applied to the original object; there is no "address in memory" aspect anywhere explicitly in the reference.