473,387 Members | 1,844 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Why Can I Modify A const std::vector& ???

I'm confused about const references. I thought they provided a way to
give access to private members without allowing those members to be
changed. However, the following client code successfully deletes the
referred to member vector:

PointCollection pc;
pc.addSomePoints();
std::vector<Point> mem = pc.getPoints(); //returns a const ref
cout << mem.size() << endl; //outputs 3, or whatever # of
points happens to be
mem.clear();
cout << mem.size() << endl; //outputs 0!!

Here is the the class in question:

class PointCollection {
private:
std::vector<int> m_points;
public:
const std::vector<Point>& PointCollection::getPoints()
{
return m_points;
}
//other methods to add points, etc, left out for
brevity
}

Thanks for any help,
cpp

Jul 23 '05 #1
12 2269
cppaddict wrote:
I'm confused about const references. I thought they provided a way to
give access to private members without allowing those members to be
changed. However, the following client code successfully deletes the
referred to member vector:

PointCollection pc;
pc.addSomePoints();
std::vector<Point> mem = pc.getPoints(); //returns a const ref
cout << mem.size() << endl; //outputs 3, or whatever # of
points happens to be
mem.clear();
cout << mem.size() << endl; //outputs 0!!

Here is the the class in question:

class PointCollection {
private:
std::vector<int> m_points;
public:
const std::vector<Point>& PointCollection::getPoints()
{
return m_points;
}
//other methods to add points, etc, left out for
brevity
}

Thanks for any help,
cpp


The following line is not doing what you think it is doing:
std::vector<Point> mem = pc.getPoints(); //returns a const ref

Your "getPoints" member may indeed be returning a constant reference,
but it is being used to initialize a vector of Points. That is, you are
making a copy (via vector's copy constructor) of whatever getPoints
returns a reference to, and then operating on that copy. If you just
want a reference you can use locally, try:
const std::vector<Point> &mem = pc.getPoints();

Alan
Jul 23 '05 #2


cppaddict wrote:
I'm confused about const references. I thought they provided a way to
give access to private members without allowing those members to be
changed. However, the following client code successfully deletes the
referred to member vector:

PointCollection pc;
pc.addSomePoints();
std::vector<Point> mem = pc.getPoints(); //returns a const ref


Here you are invoking the copy constructor on 'mem'. Now, 'mem' is a
*copy* of 'pc.getPoints()'. It is not itself a const reference. That
would look like this:

const std::vector<Point>& mem = pc.getPoints();

/david

Jul 23 '05 #3
Your "getPoints" member may indeed be returning a constant reference,
but it is being used to initialize a vector of Points. That is, you are
making a copy (via vector's copy constructor) of whatever getPoints
returns a reference to, and then operating on that copy. If you just
want a reference you can use locally, try:
const std::vector<Point> &mem = pc.getPoints();


Alan,

Thank you very much. That is exactly what I want.

cpp

Jul 23 '05 #4
One more thing...

I changed the code to:

const std::vector<Point>& mem = pc.getPoints();

and then used that ref to alter m_points. The compiler issues a
warning, but allows me to do it. And now the code really is changing
the member vector. Is const just a suggestion, rather than an
enforcable rule?

Thanks,
cpp
Jul 23 '05 #5
cppaddict <he***@hello.com> wrote in
news:3a********************************@4ax.com:
One more thing...

I changed the code to:

const std::vector<Point>& mem = pc.getPoints();

and then used that ref to alter m_points. The compiler issues a
warning, but allows me to do it. And now the code really is changing
the member vector. Is const just a suggestion, rather than an
enforcable rule?


Show us how you are modifying m_points, and what's the warning that the
compiler is issuing?
Jul 23 '05 #6
"cppaddict" <he***@hello.com> wrote in message
news:3a********************************@4ax.com
One more thing...

I changed the code to:

const std::vector<Point>& mem = pc.getPoints();

and then used that ref to alter m_points. The compiler issues a
warning, but allows me to do it. And now the code really is changing
the member vector. Is const just a suggestion, rather than an
enforcable rule?


No. Using VC++ 7.1, the

mem.clear();

call won't compile for me. What compiler are you using and what is your
*exact* code.
--
John Carson

Jul 23 '05 #7
>No. Using VC++ 7.1, the

mem.clear();

call won't compile for me. What compiler are you using and what is your
*exact* code.


Hey John.

The following code, compiled with Borland, issues a warning on the
call to clear but compiles. The output is 3 and 0, so it is
definitley altering the member vector. "Point" is a custom class
similar to the POINT of winAPI, though I don't think it's relevant:

const std::vector<Point>& mem = pc.getPoints(); //returns a
const ref
cout << mem.size() << endl; //outputs 3, or whatever # of
mem.clear();
const std::vector<Point>& mem2 = pc.getPoints(); //returns a
const ref
cout << mem2.size() << endl; //outputs 0!!

Also, here is the signature of getPoints:

const std::vector<Point>& getPoints() const;

Thanks for any more info,
cpp

Jul 23 '05 #8
cppaddict wrote:

The following code, compiled with Borland, issues a warning on the
call to clear but compiles. The output is 3 and 0, so it is
definitley altering the member vector. const std::vector<Point>& mem = pc.getPoints();
mem.clear();


You should treat that compiler warning as an error.
(In C and C++, compilers are allowed to still produce some sort
of program that may not do what you intended, as long as they
produce a diagnostic message reporting the violation).

Jul 23 '05 #9
"cppaddict" <he***@hello.com> wrote in message
news:kl********************************@4ax.com
No. Using VC++ 7.1, the

mem.clear();

call won't compile for me. What compiler are you using and what is
your *exact* code.


Hey John.

The following code, compiled with Borland, issues a warning on the
call to clear but compiles. The output is 3 and 0, so it is
definitley altering the member vector. "Point" is a custom class
similar to the POINT of winAPI, though I don't think it's relevant:

const std::vector<Point>& mem = pc.getPoints(); //returns a
const ref
cout << mem.size() << endl; //outputs 3, or whatever # of
mem.clear();
const std::vector<Point>& mem2 = pc.getPoints(); //returns a
const ref
cout << mem2.size() << endl; //outputs 0!!

Also, here is the signature of getPoints:

const std::vector<Point>& getPoints() const;

Thanks for any more info,
cpp

This is simply non-compliant behaviour on the part of the compiler. It
should not compile.

--
John Carson

Jul 23 '05 #10
This is simply non-compliant behaviour on the part of the compiler. It
should not compile.


Thanks, John.

Kind of surprising for Borland....
cpp

Jul 23 '05 #11
John Carson wrote:

This is simply non-compliant behaviour on the part of the compiler. It
should not compile.


The rule is that a compiler must issue a diagnostic. There is no
requirement in the language defintion that a compiler refuse to compile
anything.

--

Pete Becker
Dinkumware, Ltd. (http://www.dinkumware.com)
Jul 23 '05 #12
class PointCollection {
private:
std::vector<int> m_points;
....
}

are you sure you want this to be a vector<int> and not a vector<Point>

Jul 23 '05 #13

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

Similar topics

9
by: zhou | last post by:
Hi there, I am expecting that the following assignment will invoke assignment operator on vector (since myFunc() returns a const vector & type), which makes a copy of the vector returned from...
4
by: The Directive | last post by:
I can't understand why in this folling example the message "Base.Draw()" is printed. Shouldn't "Derive.Draw" be printed because of polymorphism? How can I rewrite this example using a vector to...
8
by: Maximus | last post by:
Hi, I was wondering if it is bad to overuse the new & delete operator. In my application, e.g. I created my own list class and I will have to resize my variable maybe like 100 times during runtime...
9
by: Baloff | last post by:
Hello group Is there a library which can help in doing the task below or do I need to write something up? I need to get the index of the relative “local” maximas and minimas in a sequence or...
0
by: Johannes Unfried | last post by:
Problem Best practice needed to marshal STL data from managed code to unmanaged code & vice vers Details managed code is written in managed C++ & accesses the unmanaged code (i.e. lives in a...
6
by: AzizMandar | last post by:
There is probably a better way to do this and if so I'm just as happy to see that way. I have a program where I have factories that each create various objects abstracted from a base class. ...
8
by: sagi.perel | last post by:
I have tried to compile the following code on Win & Unix. Doesn't work on either. <----- CODE -----> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <vector> #include...
9
by: miaohua1982 | last post by:
the program is as follows: #include <vector> using namespace std; class A{}; int main() { A* const &p = NULL; vector<A*B(3,NULL); //there is a compile error B.push_back(NULL);
7
by: mscava | last post by:
Hi... Today I was trying to find the best way to handle elements in Containers. I've found 3 appraoches but all do have pros and cons... 1. std::vector<MyClass> - inefficient - you have to...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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,...
0
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...

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.