473,473 Members | 2,100 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

const and non-const variables

Hi!

I always see code written like this:

void foo()
{
int b = bar();
int g = goo();
// k and g is never changed
//...
}

instead of using const

void foo()
{
const int b = bar();
const int g = goo();
// k and g is never changed
//...
}

IMO we should use const whenever is possible or am I wrong?

class Foo {
std::string var;
public:
//...
const std::string& get_var() const { return var; }
}

Foo f;
what should I use?
this:
const std::string s = f.var()
or this:
const std::string& s = f.var()
Jan 29 '06 #1
6 1632
Hi,

I understand
-> // k and g is never changed
meant
// b and g is never changed

and
-> const std::string s = f.var()
is
const std::string s = f.get_var()

This might be example of taking const to extreme.

In my view when u get reference to your private member,
it enables any external program to modify your private memebers!!
Which is not good...

e.g.

std::string modify = f.get_var() ; // /returns std::string&
modify = std::string("garbage"); << -- What happens now ??)? ( not
const )

So it is better to return copy of ur privates.

Long explanation
--------------------------
#include <string>
#include <iostream>

class A {
std::string name;
public:
A(std::string& in): name(in) {}
std::string& getA(void) { return name; }
};

int main()
{
std::string inStr(" this is good");
A test(inStr);
test.getA() = std::string(" bad bad");
std::cout << " value " << test.getA() << std::endl;
}
------------------------------
bye
ketan

Jan 30 '06 #2

"Filipe Sousa" <fi****@ipb.pt> wrote in message
news:43***********************@news.telepac.pt...
Hi!

I always see code written like this:

void foo()
{
int b = bar();
int g = goo();
// k and g is never changed
//...
}

instead of using const

void foo()
{
const int b = bar();
const int g = goo();
// k and g is never changed
//...
}

IMO we should use const whenever is possible or am I wrong?
It is extremely important to be rigorously const-correct at interfaces. It
is far less important in implementations.

class Foo {
std::string var;
public:
//...
const std::string& get_var() const { return var; }
}

Foo f;
what should I use?
this:
const std::string s = f.var()
or this:
const std::string& s = f.var()


The reference version *might* be faster, but the resulting reference is
dependent on f. Copying the string is less likely to produce hard to find
errors when f is destroyed or modified in some other way (perhaps as a
result of a change to the code which made by somebody else in the far
future).
Jan 30 '06 #3
Cy Edmunds wrote:
"Filipe Sousa" <fi****@ipb.pt> wrote in message
news:43***********************@news.telepac.pt...
Hi!

I always see code written like this:

void foo()
{
int b = bar();
int g = goo();
// k and g is never changed
//...
}

instead of using const

void foo()
{
const int b = bar();
const int g = goo();
// k and g is never changed
//...
}

IMO we should use const whenever is possible or am I wrong?


It is extremely important to be rigorously const-correct at interfaces. It
is far less important in implementations.


But it might be a hint to the user or the programmer when inspecting the
source code that b and g will never change. I don't know if the compiler
does any optimization when we use const int b instead of int b.
class Foo {
std::string var;
public:
//...
const std::string& get_var() const { return var; }
}

Foo f;
what should I use?
this:
const std::string s = f.var()
or this:
const std::string& s = f.var()


The reference version *might* be faster, but the resulting reference is
dependent on f. Copying the string is less likely to produce hard to find
errors when f is destroyed or modified in some other way (perhaps as a
result of a change to the code which made by somebody else in the far
future).


I understant.

--
Filipe Sousa
Jan 30 '06 #4

[snip]

IMO we should use const whenever is possible or am I wrong?
It is extremely important to be rigorously const-correct at interfaces.
It
is far less important in implementations.


But it might be a hint to the user or the programmer when inspecting the
source code that b and g will never change.


OK, who is this programmer who is inspecting the implementation? If he is
just a client of the code he is making a mistake. Any assumption he makes
about how the function is implemented is unwarranted and dangerous. He
should be looking at the interface and the documentation only. If he is
actually modifying the implementation a const here and there might be of
some help to him. Thus being const correct in the implementation has a minor
advantage.
I don't know if the compiler
does any optimization when we use const int b instead of int b.


This might result in some sort of minor efficiency improvement in some
cases. Again, being const correct in the implementation has a slight
advantage.

The importance of const correctness at the interface is much greater. It is
often critical to correct usage of the code by any client (not just a
re-implementor) and may prevent gross inefficiencies such as making backups
of large objects unneccesarily before making a call.

[snip]
Jan 30 '06 #5
Cy Edmunds wrote:
OK, who is this programmer who is inspecting the implementation? If he is
just a client of the code he is making a mistake. Any assumption he makes
about how the function is implemented is unwarranted and dangerous. He
should be looking at the interface and the documentation only. If he is
actually modifying the implementation a const here and there might be of
some help to him. Thus being const correct in the implementation has a minor
advantage.


What about peer review? It's easier to verify code correctness if the
code's intentions are made explicit, and constness helps with this. I
would consider this the primary advantage of using const within local
implementation scopes.

Luke

Jan 30 '06 #6
ketan wrote:
This might be example of taking const to extreme.
I disagree. It's entirely reasonable.
In my view when u get reference to your private member,
it enables any external program to modify your private memebers!!
Uh, no, not if it's a _const_ reference. That's kind of the point.
std::string modify = f.get_var() ; // /returns std::string&
No, it returns std::string const&. Which means that the copy
constructor is invoked, since this is initialization by value.
modify = std::string("garbage"); << -- What happens now ??)? ( not
const )
modify is modified, but the original string is untouched.
So it is better to return copy of ur privates.


If so, you haven't demonstrated why. The only difference I can think
of between returning by const& and returning by copy is that if the
result is used to initialize a const&, no copy is made but the lifetime
of the initialized reference is tied to that of the referent. Surely
there are cases where each is appropriate.

Luke

Luke

Jan 30 '06 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
by: lothar | last post by:
re: 4.2.1 Regular Expression Syntax http://docs.python.org/lib/re-syntax.html *?, +?, ?? Adding "?" after the qualifier makes it perform the match in non-greedy or minimal fashion; as few...
3
by: Mario | last post by:
Hello, I couldn't find a solution to the following problem (tried google and dejanews), maybe I'm using the wrong keywords? Is there a way to open a file (a linux fifo pipe actually) in...
25
by: Yves Glodt | last post by:
Hello, if I do this: for row in sqlsth: ________pkcolumns.append(row.strip()) ________etc without a prior:
32
by: Adrian Herscu | last post by:
Hi all, In which circumstances it is appropriate to declare methods as non-virtual? Thanx, Adrian.
8
by: Bern McCarty | last post by:
Is it at all possible to leverage mixed-mode assemblies from AppDomains other than the default AppDomain? Is there any means at all of doing this? Mixed-mode is incredibly convenient, but if I...
14
by: Patrick Kowalzick | last post by:
Dear all, I have an existing piece of code with a struct with some PODs. struct A { int x; int y; };
11
by: ypjofficial | last post by:
Hello All, So far I have been reading that in case of a polymorphic class ( having at least one virtual function in it), the virtual function call get resolved at run time and during that the...
2
by: Ian825 | last post by:
I need help writing a function for a program that is based upon the various operations of a matrix and I keep getting a "non-aggregate type" error. My guess is that I need to dereference my...
0
by: amitvps | last post by:
Secure Socket Layer is very important and useful for any web application but it brings some problems too with itself. Handling navigation between secure and non-secure pages is one of the cumbersome...
399
by: =?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?= | last post by:
PEP 1 specifies that PEP authors need to collect feedback from the community. As the author of PEP 3131, I'd like to encourage comments to the PEP included below, either here (comp.lang.python), or...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.