Weird const-ness troubles

From: James Aguilar (jfa1_at_cec.wustl.edu)
Date: 03/03/05


Date: Thu, 3 Mar 2005 02:26:00 -0600

Take the following code example:

class Array {
 double *m_array;
public:
 Array() { m_array = new double[10]; }
 double *begin() const {return m_array;}
};

int main() {
 const Array a = Array();
 double *iShouldNotExist(a.begin());
 iShouldNotExist[0] = -1000;
 return 0;
}

This code compiles and runs on g++ 3.3.3 with -pedantic and -ansi set. As I
see it, this code allows me to take an object declared as const and mess
around with its private internals because of a method call that promises
that the object will not be changed. What's up with that? I know that the
right way is to return a const double *, but shouldn't this kind of thing be
disallowed?

- JFA1



Relevant Pages

  • Re: SWIG typemap for ta-lib
    ... const double inReal ... outRealarray i think. ... In Ruby I like to use all input parameters as function parameters. ... int iStartIx = *arg6; ...
    (comp.lang.ruby)
  • Error by deleting pointers
    ... // create an array of animals ... int GetWeight() const ... class Array // the class being parameterized ...
    (microsoft.public.vc.language)
  • Re: Another question about multidimentional arrays
    ... Is the only benefit in how you visual the array in your mind in columns ... explicit Matrix(int rowCount, int columnCount) ... ATLASSERT(columnCount> 0); ... int Columnsconst ...
    (microsoft.public.vc.language)
  • Re: multi-dimentional arrays
    ... The above link contains a VS2008 project to show how to use the array. ... explicit Array2D(int rows, int columns) ... int Columnsconst ... ASSERT(m_columns> 0); ...
    (microsoft.public.vc.mfc)
  • Re: 2D const array nested functions warning question
    ... trying to make the int values of the array not modifiable in both ... I do not get this warning without the const modifiers. ... a pointer to an array of 2 const int. ...
    (comp.lang.c)