 |
C++Talk.NET C++ language newsgroups
|
| View previous topic :: View next topic |
| Author |
Message |
Sergei Zyablov Guest
|
Posted: Tue Sep 21, 2004 6:29 pm Post subject: What exactly the const keyword means in this C++ code? |
|
|
....Whether it influece the stack? What benefit it offers?
struct Record;
const Record func(){
Record res;
// ...
return res;
}
Thanks in advance.
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
|
|
| Back to top |
|
 |
mmm Guest
|
Posted: Wed Sep 22, 2004 9:58 am Post subject: Re: What exactly the const keyword means in this C++ code? |
|
|
keyword const means read only.
const returntype func() : it means that returntype is readonly (ex:
func().objMbr = 3; will failed)
-> const record func(); -> read only record returned
-> const record * func(); -> rw pointer on read only record returned
-> record *const func(); -> read only pointer on rw record returned
returntype func(const type arg,const type &arg2);
-> arg & arg2 are read only
-> arg is duplicated before call when making argument list in stack
-> arg2 is in fact a pointer visible in the method as it was the pointed
object directly (&=reference),
const &arg is very usefull when type is a class or a struct and when
arg is accessed only for read
operations to boost call perfo since it avoids the construction of a
temporary object.
Personnaly, I don't use the form &arg (without const kw) for method
arguments, i prefer declare io arguments by passing pointer explicitly (dcl
: type *pArg)
Only meaningfull for class/struct methods (no sense for global methods):
returntype func() const : it means that method doesn't modify class
instance (*this)
You can provide a method with an implementation for const operation
different from rw operation,
as following:
It is correct to write for the same class/struct:
const returntype &func() const;
returntype &func();
const is a keyword very usefull :
- it permits to increase compilation step checks,
- it's a usefull information on methods to understand what they do,
- and in some cases, most of times for implementation of base/library
objects (like array templates, string object,...) it can be used efficiently
to optimize code speed by differenciating rw of read only operations.
But I think too that const keyword is not fine enough in c++, and so it is
relatively difficult but not impossible to use correctly.
A keyword to know absolutely to success with const keyword: : mutable,
at the condition to use it only when necessary, and to use as follow:
struct/class blabla
{
mutable membertype mbr; -> it means that mbr is accessible for write
operation in a const method
}
Another thing: const has no effect on stack since you can cast a const
variable to a rw variable and so compiler reserve space for const variables.
Ex:
const int a = 0;
int &b = *(int*)&a;
b=1;
Beuurkk, you say ? you have right, it works for globals, method arguments,
stack var: but please do not use this, be kind with your compiler, and with
eyes of others (sorry for them ).
I probaly forget things ;-)
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
|
|
| Back to top |
|
 |
Victor Bazarov Guest
|
Posted: Wed Sep 22, 2004 9:59 am Post subject: Re: What exactly the const keyword means in this C++ code? |
|
|
"Sergei Zyablov" <zbl (AT) gmail (DOT) ru> wrote...
| Quote: | ...Whether it influece the stack? What benefit it offers?
|
None, in most cases.
| Quote: | struct Record;
const Record func(){
Record res;
// ...
return res;
}
|
struct C {
void foo();
void bar() const;
};
const C foobar();
int main() {
foobar().foo(); // will give an error
foobar().bar();
}
As you can see, if I declare the returned object 'const', I can't
call a non-const member function for it (thus modifying it on the
fly). That's the only "benefit" I can think of.
Victor
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
|
|
| Back to top |
|
 |
Zian Smith Guest
|
Posted: Wed Sep 22, 2004 10:04 am Post subject: Re: What exactly the const keyword means in this C++ code? |
|
|
[email]zbl (AT) gmail (DOT) ru[/email] (Sergei Zyablov) wrote in message news:<c76c8a0f.0409210306.23d554ad (AT) posting (DOT) google.com>...
| Quote: | ...Whether it influece the stack? What benefit it offers?
struct Record;
const Record func(){
Record res;
// ...
return res;
}
|
if you mean the benefits of returning a const from a function, it
essentially means you cannot use the function on the left hand side of
your expression. So in your case something like
func() = foo_record;
will be flagged by the compiler. I doubt you'll come across many
scenarios where you will have the function on the LHS of the
expression. (Maybe if you're returning a reference to a static
variable in the function, and dont want a user to modify that
variable?)
One common situation however is when you're overloading operaters.
Ensuring that the overloaded operator returns a const means you
prevent the user from doing stuff like:
a + b = c + d;
-Z.Smith
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
|
|
| Back to top |
|
 |
Francis Glassborow Guest
|
Posted: Wed Sep 22, 2004 6:38 pm Post subject: Re: What exactly the const keyword means in this C++ code? |
|
|
In article <cir2sg$ae2$1 (AT) news-reader2 (DOT) wanadoo.fr>, mmm
<mmm (AT) devbooster (DOT) com> writes
| Quote: | Another thing: const has no effect on stack since you can cast a const
variable to a rw variable and so compiler reserve space for const variables.
|
Sorry but that is entirely false. The language allows you to cast away
top level const qualification, but the consequences of doing so are
entirely the responsibility of the programmer.
Nowhere in the language is there any requirement for how local variables
shall be implemented.
| Quote: | Ex:
const int a = 0;
At this point the compiler is not required to provide any storage for a, |
however it can mark that if it does so it is entitled to place that
storage in write protected memory. As the programmer has specified that
a contains an immutable value the compiler is entitled to fold all
instances of a into a single one. Even if the function is recursive, I
think it is allowed to provide a single block of memory initialised to
zero at load time (even though a has not been declared static.
| Quote: | int &b = *(int*)&a;
The compiler is required to believe the programmer however it is not |
required to make the programmer's subsequent code work as expected.
| Quote: | Beuurkk, you say ? you have right, it works for globals, method arguments,
stack var: but please do not use this, be kind with your compiler, and with
eyes of others (sorry for them ).
|
What works? You have lied to the compiler and the results are undefined
whether it is a local variable or something else is quite irrelevant.
| Quote: |
I probaly forget things
|
--
Francis Glassborow ACCU
Author of 'You Can Do It!' see http://www.spellen.org/youcandoit
For project ideas and contributions: http://www.spellen.org/youcandoit/projects
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
|
|
| Back to top |
|
 |
jon hanson Guest
|
Posted: Wed Sep 22, 2004 6:51 pm Post subject: Re: What exactly the const keyword means in this C++ code? |
|
|
[email]zbl (AT) gmail (DOT) ru[/email] (Sergei Zyablov) wrote in message news:<c76c8a0f.0409210306.23d554ad (AT) posting (DOT) google.com>...
| Quote: | ...Whether it influece the stack? What benefit it offers?
struct Record;
const Record func(){
Record res;
// ...
return res;
}
|
well it stops the following from compiling :-
struct Record
{
int x;
};
const Record test1 ()
{
Record r; r.x = 10;
return r;
}
void useRecord (Record& r)
{
r.x = 20;
}
void test2 ()
{
useRecord (test1 ());
}
useRecord has to be changed to something like :-
void useRecord (const Record& r)
{
// r.x read-only;
}
jon
| Quote: | Thanks in advance.
|
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
|
|
| Back to top |
|
 |
Markus Elfring Guest
|
Posted: Wed Sep 22, 2004 6:53 pm Post subject: Re: What exactly the const keyword means in this C++ code? |
|
|
| Quote: | const Record func();
|
A constant return type prevents to try to change the temporary returned value.
This setting is a detail of the topic "const-correctness".
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
|
|
| Back to top |
|
 |
mmm Guest
|
Posted: Thu Sep 23, 2004 8:00 am Post subject: Re: What exactly the const keyword means in this C++ code? |
|
|
"Francis Glassborow" wrote:
| Quote: | mmm (AT) devbooster (DOT) com> writes
Another thing: const has no effect on stack since you can cast a const
variable to a rw variable and so compiler reserve space for const
variables.
Sorry but that is entirely false. The language allows you to cast away
top level const qualification, but the consequences of doing so are
entirely the responsibility of the programmer.
Nowhere in the language is there any requirement for how local variables
shall be implemented.
Sorry for this big mistake, and thanks for your sympathic response , I |
have wrote this a little too fast without serious check, resorry.
I never recommand this "style" of programming, I "just" misconjectured the
code generated by const global & local vars.
It's not entirely false, it's just at most a possible error source if C cast
are used without precautions, it "works" for method arguments for all
compilers ( ) (except for fastcall like calling conv, i don't try this
).
You have right, "Behaviour" for this case depends of compilers
implementations and target OS/processors capabilities concerning segment
protection (most of them now ).
After verif (on vc6), the poor code i gived crashes at exec time for globals
(for the reason you give: data segment protected from write op, here the
compiler should be able to see that generated code for my example can't
work, ds:[xx] is directly affected).
For const local vars, vc6 replaces directly when possible occurences of
const local&global vars calls by their values, and by the way i have
"discovered" a totally uninteresting thing( ): vc6 has a funny behaviour,
my sample code changes the constants(local const only) at compilation step
before substitutions (affectations was before displaying values)...
Ok, vc is not a reference...
Neverthe'less, sincerely thanks for your explainations and corrections.
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
|
|
| Back to top |
|
 |
Peter A. Kerzum Guest
|
Posted: Thu Sep 23, 2004 8:12 am Post subject: Re: What exactly the const keyword means in this C++ code? |
|
|
All said above being correct, I want to put a note here:
as of primary design intention 'const' keyword (actually first
named 'readonly' as of D&E) serves 2 different
purposes:
1. Covered above - to restrict access to data as read-only.
2. Applied to global or static variables - to ensure that
data will not be modified during runtime.
As this 2 cases may look identical, they are actually different.
The point here is that really const, second case data structure
might be initialized in compilation stage and put into 'code' or
'initialized data' segments that are read-only in terms of CPU.
Therefore C++ standard says that writing to memory initialy marked as
const should be considered an 'undefined behaviour'.
Eg:
int main(void)
{
const static int i=5;
int& b=const_cast<int&>(i);
b=10; // this is OK to get Segmentation violation here
return 0;
}
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
|
|
| Back to top |
|
 |
kanze@gabi-soft.fr Guest
|
Posted: Fri Sep 24, 2004 11:23 am Post subject: Re: What exactly the const keyword means in this C++ code? |
|
|
Francis Glassborow <francis (AT) robinton (DOT) demon.co.uk> wrote
| Quote: | Ex:
const int a = 0;
At this point the compiler is not required to provide any storage for
a, however it can mark that if it does so it is entitled to place that
storage in write protected memory. As the programmer has specified
that a contains an immutable value the compiler is entitled to fold
all instances of a into a single one. Even if the function is
recursive, I think it is allowed to provide a single block of memory
initialised to zero at load time (even though a has not been declared
static.
|
If the function takes the address and does something with it, different
instances in different occurances of the function are required to have
different addresses.
| Quote: | int &b = *(int*)&a;
The compiler is required to believe the programmer however it is not
required to make the programmer's subsequent code work as expected.
b=1;
Boom.
|
Maybe. If it would reliably go boom, that would be nice. More likely,
the compiler will continue to use 0 each time it sees an a, because it
knows that the value cannot change. Or sometimes it will use the new
value, and sometimes the old. (In a simple case, all of my compilers
use the old value. But I'm sure that I could, without too much
difficulty, construct cases where they mixed the values.)
--
James Kanze GABI Software http://www.gabi-soft.fr
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
|
|
| Back to top |
|
 |
kanze@gabi-soft.fr Guest
|
Posted: Fri Sep 24, 2004 11:23 am Post subject: Re: What exactly the const keyword means in this C++ code? |
|
|
"mmm" <mmm (AT) devbooster (DOT) com> wrote
| Quote: | keyword const means read only.
|
It's a bit more complicated than that. Const is part of the type
system. But I don't think that the original poster was asking about
const in general. I think he was wondering about its use on a return
value. After all, return values are rvalues, and for non-class types,
top level const is ignored on rvalues.
| Quote: | const returntype func() : it means that returntype is readonly (ex:
func().objMbr = 3; will failed)
|
If objMbr is not of class type, func().objMbr = 3 is illegal with or
without the const.
| Quote: | -> const record func(); -> read only record returned
-> const record * func(); -> rw pointer on read only record returned
-> record *const func(); -> read only pointer on rw record returned
|
Except that return values are rvalues, so top level const is ignored on
non-class types.
The only time top level const on a return value plays a role is for
class types with member functions -- you cannot call non-const member
functions on the returned object if it is declared const. I seem to
remember someone (Scott Meyers?) recommending that class type return
values be systematically declared const, since the operator= is normally
a non-const function, and you don't want to see it called on your return
value. IMHO, this makes sense, but I can't say that I've seen this
convention widely implemented.
| Quote: | returntype func(const type arg,const type &arg2);
-> arg & arg2 are read only
|
Again, top level const is ignored on function parameters in a function
declaration. It only has an effect in the body of the function.
| Quote: | -> arg is duplicated before call when making argument list in stack
-> arg2 is in fact a pointer visible in the method as it was the pointed
object directly (&=reference),
|
That is a frequent implementation. But references aren't pointers,
according to the standard.
| Quote: | const &arg is very usefull when type is a class or a struct
and when arg is accessed only for read
|
More importantly, you cannot bind a temporary to a non-const reference.
[...]
| Quote: | Another thing: const has no effect on stack since you can cast a const
variable to a rw variable and so compiler reserve space for const
variables.
Ex:
const int a = 0;
int &b = *(int*)&a;
b=1;
Beuurkk, you say ? you have right, it works for globals, method
arguments, stack var: but please do not use this, be kind with your
compiler, and with eyes of others (sorry for them ).
|
It's undefined behavior. It may work, some of the time, or it may not.
Stack or not. (In practice, I know of no compiler where it works
systematically.)
--
James Kanze GABI Software http://www.gabi-soft.fr
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
|
|
| Back to top |
|
 |
Francis Glassborow Guest
|
Posted: Fri Sep 24, 2004 2:08 pm Post subject: Re: What exactly the const keyword means in this C++ code? |
|
|
In article <cit6ov$1at$1 (AT) news-reader1 (DOT) wanadoo.fr>, mmm
<mmm (AT) devbooster (DOT) com> writes
| Quote: | "Francis Glassborow" wrote:
[email]mmm (AT) devbooster (DOT) com[/email]> writes
Another thing: const has no effect on stack since you can cast a
const
variable to a rw variable and so compiler reserve space for const
variables.
Sorry but that is entirely false. The language allows you to cast away
top level const qualification, but the consequences of doing so are
entirely the responsibility of the programmer.
Nowhere in the language is there any requirement for how local
variables
shall be implemented.
Sorry for this big mistake, and thanks for your sympathic response ,
|
Sorry if my writing style came across as being a personal criticism. I
sometimes have to swallow hard and count to ten when someone tells me
that I am entirely wrong about something, but then I move on and learn
from my error (and my increased knowledge is a direct result of my
willingness to risk being wrong)
| Quote: | I
have wrote this a little too fast without serious check, resorry.
I never recommand this "style" of programming, I "just" misconjectured
the
code generated by const global & local vars.
It's not entirely false, it's just at most a possible error source if
C cast
are used without precautions, it "works" for method arguments for all
compilers ( ) (except for fastcall like calling conv, i don't try
this
).
|
I think you may not understand the implications of undefined behaviour.
The particularly nasty aspect of it is that it often manifests by doing
exactly what the programmer expects. Then the code is compiled with a
different set of compiler switches, or a different compiler, or a new
version of the existing one and some actually nasty behaviour occurs.
Any form of cast that attempts to remove const qualification from an
object (note that a reference is not an object in itself but refers to
an object) that has been declared as const allows the compiler to be as
nasty as it likes. Of course implementors do not actually set out to be
nasty (though that might be a positive feature if the implementation was
for learning purposes only) but the language rules allow them certain
types of latitude based on the assumption that programmers do not
deliberately lie to the compiler.
I believe that const_cast should never be applied to an object but only
to a reference to const or pointer to const object. IOWs it is OK to
sometimes remove a 'read only' qualifier but never correct to remove an
immutable one. Unfortunately C++ uses the same keyword for both even
though it is always clear in context as to which meaning is intended.
What makes it harder is that there is no runtime mechanism to determine
if an object is immutable. That lack makes most uses of const_cast<>
suspect. About the only place that I would use const_cast<> is in
implementing the idiom:
mytype const * foo(mytype const *);
mytype * foo (mytype * mt){
return const_cast<mytytpe *>foo(const_cast<mytype const *>mt);
}
Whose main purpose is to prevent references to non-const objects
acquiring const qualification.
In addition I would view most uses of C style casts and function style
casts with deep suspicion. I do accept their use in a limited number of
situations in informal code. The main case being code such as:
enum colour { red=1, green=2, blue=4};
colour const yellow = colour(red + green);
--
Francis Glassborow ACCU
Author of 'You Can Do It!' see http://www.spellen.org/youcandoit
For project ideas and contributions:
http://www.spellen.org/youcandoit/projects
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
|
|
| Back to top |
|
 |
Francis Glassborow Guest
|
Posted: Fri Sep 24, 2004 2:09 pm Post subject: Re: What exactly the const keyword means in this C++ code? |
|
|
In article <d4039ed4.0409221159.7a3c76f0 (AT) posting (DOT) google.com>, Peter A.
Kerzum <kerzum (AT) mail (DOT) ru> writes
| Quote: | All said above being correct, I want to put a note here:
as of primary design intention 'const' keyword (actually first
named 'readonly' as of D&E) serves 2 different
purposes:
1. Covered above - to restrict access to data as read-only.
2. Applied to global or static variables - to ensure that
data will not be modified during runtime.
|
Why do you believe that the second case only applies to static (either
declared as static or at namespace scope) variables?
--
Francis Glassborow ACCU
Author of 'You Can Do It!' see http://www.spellen.org/youcandoit
For project ideas and contributions:
http://www.spellen.org/youcandoit/projects
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
|
|
| Back to top |
|
 |
Chris Uzdavinis Guest
|
Posted: Fri Sep 24, 2004 10:18 pm Post subject: Re: What exactly the const keyword means in this C++ code? |
|
|
[email]j0n_h4ns0n (AT) yahoo (DOT) co.uk[/email] (jon hanson) wrote in message
| Quote: | What benefit it offers?
well it stops the following from compiling :-
struct Record
{
int x;
};
const Record test1 ()
{
Record r; r.x = 10;
return r;
}
void useRecord (Record& r)
{
r.x = 20;
}
void test2 ()
{
useRecord (test1 ());
}
useRecord has to be changed to something like :-
void useRecord (const Record& r)
{
// r.x read-only;
}
|
You're correct in that the above code won't compile without your
suggested fix, but the "const" keyword on the return type of test1()
has no bearing on that. The reason your code fails to compile is that
test1() returns a temporary varaible, and you're trying to bind a
reference to a non-const object to that temporary (when passing it to
useRecord()). That is not allowed. However, binding a
reference-to-const to an unnamed temporary variable is allowed.
--
Chris
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
|
|
| Back to top |
|
 |
Francis Glassborow Guest
|
Posted: Sat Sep 25, 2004 2:50 pm Post subject: Re: What exactly the const keyword means in this C++ code? |
|
|
In article <d6652001.0409230029.2520c445 (AT) posting (DOT) google.com>,
[email]kanze (AT) gabi-soft (DOT) fr[/email] writes
| Quote: | Francis Glassborow <francis (AT) robinton (DOT) demon.co.uk> wrote in message
news:<1kwSXTT$NWUBFwbM (AT) robinton (DOT) demon.co.uk>...
Ex:
const int a = 0;
At this point the compiler is not required to provide any storage for
a, however it can mark that if it does so it is entitled to place that
storage in write protected memory. As the programmer has specified
that a contains an immutable value the compiler is entitled to fold
all instances of a into a single one. Even if the function is
recursive, I think it is allowed to provide a single block of memory
initialised to zero at load time (even though a has not been declared
static.
If the function takes the address and does something with it, different
instances in different occurances of the function are required to have
different addresses.
|
I am not going to say you are mistaken, but where is that requirement in
the C++ Standard? And does that requirement also apply to cases where
the const object is referenced?
Given that it is undefined behaviour to modify a const instance, and
that there is no non-trivial construction/destruction semantics for
instances of fundamental types the only remaining potential is for
comparison of the pointers to two instances. Even simultaneous reads in
different threads running on different processors should not be
problematic.
In order to obtain the addresses of two instances the function has to be
recursive. Any old recursive function is not enough, it has to either
store that address in a non-local object or it must have a suitable
parameter by which the address can be acquired.
Unless there is a good counter-example, I think I would argue that a
compiler should be allowed to treat physically const objects of
fundamental types and types with trivial ctors/dtors as static objects.
--
Francis Glassborow ACCU
Author of 'You Can Do It!' see http://www.spellen.org/youcandoit
For project ideas and contributions: http://www.spellen.org/youcandoit/projects
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
|
|
| Back to top |
|
 |
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
|