const &

  • Thread starter Marcin Vorbrodt
  • Start date
M

Marcin Vorbrodt

I understand that compiler may optimize better, if as parameters to my
functions i pass:

const Object &o

instead of

Object &o

All the implicit type conversion and all sounds good (Effective C++ rules).

But, does it make any difference if i do simillar thing for primitive types:

function(int x) vs function(const int x)

and i know that x will not be assigned to in the body of the function.
Is there any advantage at all in putting the const qualifier for primitives?

Thanks,
Martin
 
K

Kevin Goodsell

Marcin said:
I understand that compiler may optimize better, if as parameters to my
functions i pass:

const Object &o

instead of

Object &o

I don't know about that. But it does make the function more flexible
since you can pass temporaries and constant objects. There's also no
good reason to /not/ use const here, if you don't intend to change the
object.
All the implicit type conversion and all sounds good (Effective C++ rules).

But, does it make any difference if i do simillar thing for primitive types:

function(int x) vs function(const int x)

and i know that x will not be assigned to in the body of the function.
Is there any advantage at all in putting the const qualifier for primitives?

I don't think so.

-Kevin
 
J

Josh Sebastian

I understand that compiler may optimize better, if as parameters to my
functions i pass:

const Object &o

instead of

Object &o

No, you (might) get better performance if you use

const Object& o

instead of

Object o

Josh
 
P

Pete Becker

Oliver S. said:
The called code is allowed to cast to a non-const reference if the
underlying object has only logical (as opposed to physical) constness.
So the compiler can assume that the object's non-mutable elements are
not changed only if the object has physical constness - which is very
unusual.

The true rule is that you can cast away const if the original object
isn't const. Otherwise you get undefined behavior. A common example is:

int main()
{
const int i = 3;
int& ir = const_cast<int&)(i);
ir = 4;
printf("%d\n", i);
return 0;
}

With some compilers this prints 3, with others 4. Both answers are
acceptable, because the behavior of the program is undefined.
 
P

Pete Becker

Oliver S. said:
That's only one of the rules which describe objects that have
logical constness.

Maybe. The obvious implication is that "logical constness" isn't the
test for casting away const.
 

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
474,141
Messages
2,570,817
Members
47,365
Latest member
BurtonMeec

Latest Threads

Top