Home > Mobile >  Does initializing references cost more memory if you copy to an lvalue less than the size of a refer
Does initializing references cost more memory if you copy to an lvalue less than the size of a refer

Time:06-21

So I believe on 64-bit systems a pointer is 8B. A float is 4B. Let's say you have the following code:

const float a = 1.0f;

Then, I want to know the cost comparison of the following. Say we have

const float b = a;

I know that copying float will be 4B. But I would think that we can 'save' memory if we don't have to copy the float. I know that if it weren't float, but instead a large object (>8B), using a reference in a similar manner would be more optimal:

const float &b = a;

However, since we are using float, is it more compact to copy to a new variable? Assuming that the compiler won't optimize anything?

const float a = b;
const float &a = b;

CodePudding user response:

If you write const float b = a; then you are making a copy of the value. Now if the type is a fundamental type or trivially copyable with no custom copy constructor the compiler can easily optimize away the copy and no actual code gets generated at all. That is unless you take the address of the obejct:

#include <iostream>

int main() {
    const float a = 1.0;
    const float b = a;
    const float &r = a;
    std::cout << "&a == &b: " << (&a == &b ? "true" : "false") << std::endl; 
    std::cout << "&a == &r: " << (&a == &r ? "true" : "false") << std::endl; 
}

gives:

&a == &b: false
&a == &r: true

As you can see a and b have different addresses. They are different objects and the compiler will have to add a copy of a named b. The reference r on the other hand is the same object as a so it has the same address. The compiler will not make a copy.

This also holds if a isn't a trivial type and the compiler can't eliminate the copy constructor. The reference is a total NOP, it just gives the existing object another name.


But don't confuse this with passing values by reference or storing references in structs or classes. Internally a reference is implemented as a pointer. If you pass a reference then you pass a copy of the pointer. If you store a reference then the pointer is stored.

Only for local references the compiler can use the original object directly.

  •  Tags:  
  • c
  • Related