triclosan
triclosan

Reputation: 5714

Constructing const object vs reference to const object

I'm curious regarding best practices. Let's assume I need to construct an object that further is not supposed to be modified:

  void fn() {
    const std::string& ref_to_const = "one";
    ...
    const std::string const_object = "two";
    ...
  }

The lifespan of both temporary object and const object will be the same. So what approach to use?

Upvotes: 0

Views: 79

Answers (2)

Jodocus
Jodocus

Reputation: 7581

So what approach to use?

Generally, the one that is more expressive: the plain const std::string.

The fact that a constant reference can bind to and extend the lifetime of a temporary value mainly exists for making call-by-reference possible for temporaries. There is no reason to make use of this in a situation like yours.

Upvotes: 6

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122133

You create an instance, and using a reference to store that instance is just obfuscating this fact. Make your code explicit: You create an instance, so declare it as an instance, not as a reference:

const std::string const_object = "two";

Upvotes: 3

Related Questions