discards qualifiers

C

Chameleon

#include <vector>

using namespace std;

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


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::eek:perator[](int)' discards qualifiers
*/
 
V

Victor Bazarov

#include <vector>

using namespace std;

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


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::eek:perator[]
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); }

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::eek:perator[](int)' discards qualifiers
*/

V
 
J

James Kanze

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); }
};
void here_it_comes(const vector<Vector> &vertex)


[...]
Declare another operator[] in Vector,
like so:
struct Vector
{
...
double operator[](int i) const { return (&x); }

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,962
Messages
2,570,134
Members
46,690
Latest member
MacGyver

Latest Threads

Top