473,597 Members | 2,413 Online
Bytes | Software Development & Data Engineering Community
+ 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 1635
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("ga rbage"); << -- 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.p t> wrote in message
news:43******** *************** @news.telepac.p t...
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.p t> wrote in message
news:43******** *************** @news.telepac.p t...
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("ga rbage"); << -- 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
4412
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 characters as possible will be matched. the regular expression module fails to perform non-greedy matches as described in the documentation: more than "as few characters as possible"
3
12216
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 nonblocking mode in c++? I did something ugly like --- c/c++ mixture --- mkfifo( "testpipe", 777);
25
7584
by: Yves Glodt | last post by:
Hello, if I do this: for row in sqlsth: ________pkcolumns.append(row.strip()) ________etc without a prior:
32
4497
by: Adrian Herscu | last post by:
Hi all, In which circumstances it is appropriate to declare methods as non-virtual? Thanx, Adrian.
8
3498
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 cannot load/unload/reload extensions into my large and slow-to-load application during development without restarting the process then the disadvantages may outweigh the advantages. I've got a mixed-mode program in which I create a new AppDomain...
14
8384
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
3414
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 vtable pointer is made use of.. eg. class one {
2
6102
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 pointers, but I'm not sure. Please help. The code: void equate(matrix *A, matrix *B) { int i, j; assert(A.row_dim == B.col_dim && A.col_dim == B.col_dim); for(i=0; i < A.row_dim; i++) for(j=0; j < A.col_dim; j++)
0
2327
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 jobs. When a non-secure page references a secure page with relative URL, the web server generates error until absolute URL with https prefix is used. On the other hand when a secure page references a non-secure page, the non-secure page will be...
399
12757
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 to python-3000@python.org In summary, this PEP proposes to allow non-ASCII letters as identifiers in Python. If the PEP is accepted, the following identifiers would also become valid as class, function, or variable names: Löffelstiel,...
0
7883
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8379
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8021
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
6677
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
3876
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
3917
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2393
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 we have to send another system
1
1492
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1226
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.