iouvxz
iouvxz

Reputation: 163

C++ cost of declaring a reference?

Does declaring a reference result in runtime costs ?

Typename a;    
auto& b=a;
func(b);

Does declaring a reference inside of a loop result in multiple times of runtime costs ?

Typename a=Typename();//default constructor
for(int i=0;i<100;i++)
{
    auto& b=a;
    func(b);
}

Or

Typename a=Typename();//default constructor
auto& b=a;
for(int i=0;i<100;i++)
{
    func(b);
}

better?

Upvotes: 2

Views: 843

Answers (1)

ajshort
ajshort

Reputation: 3764

Underneath the hood, references are generally implemented using a pointer - so there may be the additional cost imposed by this (the memory cost of the pointer, as well as the runtime cost of the de-reference operation). However, if the reference is used only as a local alias (as you are doing here), compilers are capable of completely optimising this out.

This behaviour though can depend on your compiler and optimisation settings. For your specific example: Using GCC 5.2, with optimisation disabled the reference inside the loop generates an additional de-reference operation. However, as soon as you turn on optimisation they both generate identical output.

Upvotes: 1

Related Questions