0

I understand that it is better to pass const String references as arguments to methods.

However, if I just need to use a String as a constant in the code, is it still better to reference it? Isn't it just an overhead to get a reference to it? I can see this in a number of places in our code base and I'm trying to understand why this would be desirable.

string bar = "test";
const string& data = "FOO_" + bar; //why is this better than const string data?
insert(data)

The function insert takes a reference,

void insert(const string& data)

The same question would apply to any const object being used in the same fashion.

Thanks!

3
  • 1
    Maybe I'm crazy but I think const string & data = "FOO_" + bar; doesn't work. Commented Jul 24, 2015 at 21:49
  • @QuestionC Why does not it work? Commented Jul 24, 2015 at 21:51
  • A const reference rarely has any overhead. The compiler will know to optimize it. Commented Jul 24, 2015 at 21:54

2 Answers 2

1
const string data = "FOO_" + bar;

Creates a temporary and passes her as argument to the copy ctor of data on construction. Creates two string instances, does a copy and destructs one instance.

const string& data = "FOO_" + bar;

Creates a temporary but assigns her to name data, so she isn't temporary anymore. One instance created, not more.

Sign up to request clarification or add additional context in comments.

1 Comment

The first case may be eligible for RVO, so the result of operator+ may be directly constructed into data, bypassing the copy.
1

A reference in C++ should be thought of as an alias for an existing variable. You use a reference when you have a variable that already exists that you would like to access by a different alias (name).

This is most common in function calls when you would like to refer to an existing variable (memory location) as an argument to a function. If you do not want to pass a copy to the function, and you instead want to pass an already existing variable to the function under a new name that is when you use a reference.

Similarly, when you want a class to refer to a variable that already exists you use a reference.

A reference 'should' always refer to an existing variable.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.