const type& and type const&

P

p|OtrEk

What is practic difference between this two declarations?
If i want call my func with func("blah") i could write:
1) func(std::string const& arg1)
2) func(const std::string& arg1)
Whats better to use if i dont want to change content of arg1 it in func
body?
 
B

Ben Pope

p|OtrEk said:
What is practic difference between this two declarations?
If i want call my func with func("blah") i could write:
1) func(std::string const& arg1)
2) func(const std::string& arg1)
Whats better to use if i dont want to change content of arg1 it in func
body?

They're the same.

The types are read from right to left.

consider:

const int i; // i is a const int
int const i; // i is a const int
const int * i // i is a pointer to a const int.
int const * i // i is a pointer to a const int
int * const i // i is a const pointer to an int
const int * const i // i is a const pointer to a const int
int const * const i // i is a const pointer to a const int

References cannot be reseated (c.f., pointers), so they are already "const".

It's usually easier to read:
const int i;

yet, when stacking them up, it's usually easier the other way around:
int const * const

Ben
 
L

lysek

On more thing,
is this legal to write:
const int& fun () { return 1; } // so it returns reference to const '1'
??
 
B

Ben Pope

lysek said:
On more thing,
is this legal to write:
const int& fun () { return 1; } // so it returns reference to const '1'

You'd be returning a reference to a local... it would have lost it's scope by the time the function returned. This is undefined behavious, as far as I know.

It's usually best/safest to return by value.

Ben
 
M

Mercator

Ben said:
You'd be returning a reference to a local... it would have lost it's scope by the time the function returned. This is undefined behavious, as far as I know.

1 is an integer literal, not a local variable.
 
B

Ben Pope

Mercator said:
1 is an integer literal, not a local variable.

Yeah, I guessed somebody would mention that when I hit send. I was kind of extrapolating his use from the previous example, I guess this is why posting ACTUAL code rather than
noddy examples that are supposed to be equivalent, but aren't, is never a good idea.

Ben
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top