Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

discards qualifiers

52 views
Skip to first unread message

Chameleon

unread,
Nov 17, 2010, 2:22:34 PM11/17/10
to
#include <vector>

using namespace std;

struct Vector
{
double x,y,z;
double &operator[](int i) { return (&x)[i]; }
};


void here_it_comes(const vector<Vector> &vertex)
{
double a = vertex[0][0]; // compile error
double b = const_cast<Vector&>(vertex[0])[0]; // no problem, but why
the need not to be const? I change it nowhere.
}


int main() { return 0; };
/*
1.cpp: In function 'void here_it_comes(const std::vector<Vector,
std::allocator<Vector> >&)':
1.cpp:14: error: passing 'const Vector' as 'this' argument of 'double&
Vector::operator[](int)' discards qualifiers
*/

Victor Bazarov

unread,
Nov 17, 2010, 2:47:28 PM11/17/10
to
On 11/17/2010 2:22 PM, Chameleon wrote:
> #include <vector>
>
> using namespace std;
>
> struct Vector
> {
> double x,y,z;
> double &operator[](int i) { return (&x)[i]; }
> };
>
>
> void here_it_comes(const vector<Vector> &vertex)

'vertex' refers to a constant vector. That means that the operator[] of
it returns a reference to a *constant* Vector. Your Vector::operator[]
is non-const (since it is apparently designed to allow putting it on the
left side of the assignment operator). Declare another operator[] in
Vector, like so:

struct Vector
{
...
double operator[](int i) const { return (&x)[i]; }

and it's going to be OK.

> {
> double a = vertex[0][0]; // compile error
> double b = const_cast<Vector&>(vertex[0])[0]; // no problem, but why the
> need not to be const? I change it nowhere.
> }
>
>
> int main() { return 0; };
> /*
> 1.cpp: In function 'void here_it_comes(const std::vector<Vector,
> std::allocator<Vector> >&)':
> 1.cpp:14: error: passing 'const Vector' as 'this' argument of 'double&
> Vector::operator[](int)' discards qualifiers
> */

V
--
I do not respond to top-posted replies, please don't ask

James Kanze

unread,
Nov 18, 2010, 5:46:31 AM11/18/10
to
On Nov 17, 7:47 pm, Victor Bazarov <v.baza...@comcast.invalid> wrote:
> On 11/17/2010 2:22 PM, Chameleon wrote:

> > #include <vector>

> > using namespace std;

> > struct Vector
> > {
> > double x,y,z;
> > double &operator[](int i) { return (&x)[i]; }
> > };

> > void here_it_comes(const vector<Vector> &vertex)

[...]


> Declare another operator[] in Vector,
> like so:

> struct Vector
> {
> ...
> double operator[](int i) const { return (&x)[i]; }

> and it's going to be OK.

But only if i is 0 (as it is in his test program). Otherwise,
he has undefined behavior.

--
James Kanze

0 new messages