What a pointer really points to

Discussion in 'C++' started by Steven T. Hatton, Dec 9, 2006.

  1. I found the example code below, listed in the book described here:
    http://cartan.cas.suffolk.edu/moin/OopDocbookWiki

    The result was a bit surprising. I guess it falls into the category
    of "that's what you get for lying". Can the behavior demonstrated be
    explained in standardese? Yes, I know the exact result is "undefined
    behavior". I can see what happened. But what was the actual violation?

    // Miles are converted to kilometers.
    #include <QTextStream>

    QTextStream cin(stdin, QIODevice::ReadOnly);
    QTextStream cout(stdout, QIODevice::WriteOnly);
    QTextStream cerr(stderr, QIODevice::WriteOnly);

    const double m2k = 1.609; // conversion constant

    inline double mi2km(int miles) {
    return (miles * m2k);
    }

    int main() {
    int miles;
    double kilometers;
    cout << "Enter distance in miles: " << flush;
    cin >> miles ;
    kilometers = mi2km(miles);
    cout << "This is approximately "
    << static_cast<int>(kilometers)
    << "km."<< endl;
    cout << "Without the cast, kilometers = "
    << kilometers << endl;
    double* dp = const_cast<double*>(&m2k);
    cout << "m2k: " << m2k << endl;
    cout << "&m2k: " << &m2k << " dp: " << dp << endl;
    cout << "*dp: " << *dp << endl;
    *dp = 1.892; /* What are we attempting to do here?*/
    cout << "Can we reach this statement? " << endl;
    return 0;
    }

    /*OUT
    Enter distance in miles: 23
    This is approximately 37km.
    Without the cast, kilometers = 37.007
    m2k: 1.609
    &m2k: 0x8049048 dp: 0x8049048
    *dp: 1.609
    Segmentation fault
    */


    --
    NOUN:1. Money or property bequeathed to another by will. 2. Something handed
    down from an ancestor or a predecessor or from the past: a legacy of
    religious freedom. ETYMOLOGY: MidE legacie, office of a deputy, from OF,
    from ML legatia, from L legare, to depute, bequeath. www.bartleby.com/61/
     
    Steven T. Hatton, Dec 9, 2006
    #1
    1. Advertising

  2. Steven T. Hatton

    kwikius Guest

    Steven T. Hatton wrote:
    > I found the example code below, listed in the book described here:
    > http://cartan.cas.suffolk.edu/moin/OopDocbookWiki


    Well that just goes to show you don't it ;-)

    #include <quan/out/length.hpp>

    int main() {


    std::cout << "Enter distance in miles: ";
    quan::length::mi miles;
    std::cin >> miles.reference_numeric_value<quan::length::mi>(); ;
    quan::length::km kilometers = miles;
    std::cout << "\nThat is approximately " << kilometers << "\n\n";

    std::cout << "Can we reach this statement?\n\n";
    std::cout << "Sure! ... Feel the Power of The Quan :)\n\n";
    std::cout << "-------------------------------------\n";
    std::cout << "Quan documentation :\n\n";
    std::cout << "<http://quan.sourceforge.net>\n\n";
    std::cout << "Quan download and cvs :\n\n";
    std::cout << "<http://sourceforge.net/projects/quan>\n\n";
    std::cout << "-------------------------------------\n";
    return 0;
    }
    /*
    output:
    Enter distance in miles: 2

    That is approximately 3.21869 km

    Can we reach this statement?

    Sure! ... Feel the Power of The Quan :)

    -------------------------------------
    Quan documentation :

    <http://quan.sourceforge.net>

    Quan download and cvs :

    <http://sourceforge.net/projects/quan>

    -------------------------------------
    */
     
    kwikius, Dec 9, 2006
    #2
    1. Advertising

  3. Steven T. Hatton

    John Carson Guest

    "Steven T. Hatton" <> wrote in message
    news:
    > I found the example code below, listed in the book described here:
    > http://cartan.cas.suffolk.edu/moin/OopDocbookWiki
    >
    > The result was a bit surprising. I guess it falls into the category
    > of "that's what you get for lying". Can the behavior demonstrated be
    > explained in standardese? Yes, I know the exact result is "undefined
    > behavior". I can see what happened. But what was the actual
    > violation?
    >
    > // Miles are converted to kilometers.
    > #include <QTextStream>
    >
    > QTextStream cin(stdin, QIODevice::ReadOnly);
    > QTextStream cout(stdout, QIODevice::WriteOnly);
    > QTextStream cerr(stderr, QIODevice::WriteOnly);
    >
    > const double m2k = 1.609; // conversion constant
    >
    > inline double mi2km(int miles) {
    > return (miles * m2k);
    > }
    >
    > int main() {
    > int miles;
    > double kilometers;
    > cout << "Enter distance in miles: " << flush;
    > cin >> miles ;
    > kilometers = mi2km(miles);
    > cout << "This is approximately "
    > << static_cast<int>(kilometers)
    > << "km."<< endl;
    > cout << "Without the cast, kilometers = "
    > << kilometers << endl;
    > double* dp = const_cast<double*>(&m2k);
    > cout << "m2k: " << m2k << endl;
    > cout << "&m2k: " << &m2k << " dp: " << dp << endl;
    > cout << "*dp: " << *dp << endl;
    > *dp = 1.892; /* What are we attempting to do here?*/
    > cout << "Can we reach this statement? " << endl;
    > return 0;
    > }
    >
    > /*OUT
    > Enter distance in miles: 23
    > This is approximately 37km.
    > Without the cast, kilometers = 37.007
    > m2k: 1.609
    > &m2k: 0x8049048 dp: 0x8049048
    > *dp: 1.609
    > Segmentation fault
    > */


    Deleting the irrelevant, you have:

    const double m2k = 1.609;

    int main()
    {
    double* dp = const_cast<double*>(&m2k);
    *dp = 1.892;
    return 0;
    }

    Thus dp points to a const variable and you attempt to change that const
    variable using a dereferenced dp.

    The operating system has presumably stored m2k in a read-only section of
    memory, so raises a segmentation fault when you attempt to write to that
    memory.

    --
    John Carson
     
    John Carson, Dec 9, 2006
    #3
  4. John Carson wrote:

    > "Steven T. Hatton" <> wrote in message
    > news:
    >> I found the example code below, listed in the book described here:
    >> http://cartan.cas.suffolk.edu/moin/OopDocbookWiki
    >>
    >> The result was a bit surprising. I guess it falls into the category
    >> of "that's what you get for lying". Can the behavior demonstrated be
    >> explained in standardese? Yes, I know the exact result is "undefined
    >> behavior". I can see what happened. But what was the actual
    >> violation?
    >>
    >> // Miles are converted to kilometers.
    >> #include <QTextStream>
    >>
    >> QTextStream cin(stdin, QIODevice::ReadOnly);
    >> QTextStream cout(stdout, QIODevice::WriteOnly);
    >> QTextStream cerr(stderr, QIODevice::WriteOnly);
    >>
    >> const double m2k = 1.609; // conversion constant
    >>
    >> inline double mi2km(int miles) {
    >> return (miles * m2k);
    >> }
    >>
    >> int main() {
    >> int miles;
    >> double kilometers;
    >> cout << "Enter distance in miles: " << flush;
    >> cin >> miles ;
    >> kilometers = mi2km(miles);
    >> cout << "This is approximately "
    >> << static_cast<int>(kilometers)
    >> << "km."<< endl;
    >> cout << "Without the cast, kilometers = "
    >> << kilometers << endl;
    >> double* dp = const_cast<double*>(&m2k);
    >> cout << "m2k: " << m2k << endl;
    >> cout << "&m2k: " << &m2k << " dp: " << dp << endl;
    >> cout << "*dp: " << *dp << endl;
    >> *dp = 1.892; /* What are we attempting to do here?*/
    >> cout << "Can we reach this statement? " << endl;
    >> return 0;
    >> }
    >>
    >> /*OUT
    >> Enter distance in miles: 23
    >> This is approximately 37km.
    >> Without the cast, kilometers = 37.007
    >> m2k: 1.609
    >> &m2k: 0x8049048 dp: 0x8049048
    >> *dp: 1.609
    >> Segmentation fault
    >> */

    >
    > Deleting the irrelevant, you have:


    It's often nice to have something that actually compiles and runs.
    Compiling the code using the Standard Library would take a trivial amount
    of effort.

    > const double m2k = 1.609;
    >
    > int main()
    > {
    > double* dp = const_cast<double*>(&m2k);
    > *dp = 1.892;
    > return 0;
    > }
    >
    > Thus dp points to a const variable


    What does the Standard specify it should point to, or is that specified?

    > and you attempt to change that const
    > variable using a dereferenced dp.
    >
    > The operating system has presumably stored m2k in a read-only section of
    > memory, so raises a segmentation fault when you attempt to write to that
    > memory.


    As I sated, I understand what happened. I'm just not sure what rule was
    violated. I guess I go back to slogging my way through the artful prose of
    the formal arcana of the Standard.

    --
    NOUN:1. Money or property bequeathed to another by will. 2. Something handed
    down from an ancestor or a predecessor or from the past: a legacy of
    religious freedom. ETYMOLOGY: MidE legacie, office of a deputy, from OF,
    from ML legatia, from L legare, to depute, bequeath. www.bartleby.com/61/
     
    Steven T. Hatton, Dec 9, 2006
    #4
  5. Steven T. Hatton

    kwikius Guest

    Steven T. Hatton wrote:

    > What does the Standard specify it should point to, or is that specified?


    The only time you can use const_cast on some object reference is when
    you *know* that the real object is not const. Any const cast on a
    physically const object results in undefined behaviour. The better
    option on stuff you *own* is to use mutable: That is my understanding
    anyway:

    struct my{
    private:
    int n;
    public:
    my():n(1),y(2){}
    // mod is declared as a const function
    // but maybe want to keep internal count
    void mod1()const
    {
    // dodgy If someone declares a const my
    my& mm = const_cast<my&>(*this);
    ++mm.n;
    }
    private:
    mutable int y;
    public:
    void mod2()const
    { // always ok
    ++y;
    }
    };

    int main()
    {
    my x;
    x.mod1();
    x.mod2();
    }

    regards
    Andy Little
     
    kwikius, Dec 9, 2006
    #5
  6. Steven T. Hatton

    kwikius Guest

    Steven T. Hatton wrote:

    > What does the Standard specify it should point to, or is that specified?


    The only time you can use const_cast on some object reference is when
    you *know* that the real object is not const. Any const cast on a
    physically const object results in undefined behaviour. The better
    option on stuff you *own* is to use mutable: That is my understanding
    anyway:

    struct my{
    private:
    int n;
    public:
    my():n(1),y(2){}
    // mod is declared as a const function
    // but maybe want to keep internal count
    void mod1()const
    {
    // dodgy If someone declares a const my
    my& mm = const_cast<my&>(*this);
    ++mm.n;
    }
    private:
    mutable int y;
    public:
    void mod2()const
    { // always ok
    ++y;
    }
    };

    int main()
    {
    my x;
    x.mod1();
    x.mod2();
    }

    regards
    Andy Little
     
    kwikius, Dec 9, 2006
    #6
  7. Steven T. Hatton

    Kai-Uwe Bux Guest

    Steven T. Hatton wrote:

    > John Carson wrote:
    >
    >> "Steven T. Hatton" <> wrote in message
    >> news:
    >>> I found the example code below, listed in the book described here:
    >>> http://cartan.cas.suffolk.edu/moin/OopDocbookWiki
    >>>
    >>> The result was a bit surprising. I guess it falls into the category
    >>> of "that's what you get for lying". Can the behavior demonstrated be
    >>> explained in standardese? Yes, I know the exact result is "undefined
    >>> behavior". I can see what happened. But what was the actual
    >>> violation?
    >>>
    >>> // Miles are converted to kilometers.
    >>> #include <QTextStream>
    >>>
    >>> QTextStream cin(stdin, QIODevice::ReadOnly);
    >>> QTextStream cout(stdout, QIODevice::WriteOnly);
    >>> QTextStream cerr(stderr, QIODevice::WriteOnly);
    >>>
    >>> const double m2k = 1.609; // conversion constant
    >>>
    >>> inline double mi2km(int miles) {
    >>> return (miles * m2k);
    >>> }
    >>>
    >>> int main() {
    >>> int miles;
    >>> double kilometers;
    >>> cout << "Enter distance in miles: " << flush;
    >>> cin >> miles ;
    >>> kilometers = mi2km(miles);
    >>> cout << "This is approximately "
    >>> << static_cast<int>(kilometers)
    >>> << "km."<< endl;
    >>> cout << "Without the cast, kilometers = "
    >>> << kilometers << endl;
    >>> double* dp = const_cast<double*>(&m2k);
    >>> cout << "m2k: " << m2k << endl;
    >>> cout << "&m2k: " << &m2k << " dp: " << dp << endl;
    >>> cout << "*dp: " << *dp << endl;
    >>> *dp = 1.892; /* What are we attempting to do here?*/
    >>> cout << "Can we reach this statement? " << endl;
    >>> return 0;
    >>> }
    >>>
    >>> /*OUT
    >>> Enter distance in miles: 23
    >>> This is approximately 37km.
    >>> Without the cast, kilometers = 37.007
    >>> m2k: 1.609
    >>> &m2k: 0x8049048 dp: 0x8049048
    >>> *dp: 1.609
    >>> Segmentation fault
    >>> */

    >>
    >> Deleting the irrelevant, you have:

    >
    > It's often nice to have something that actually compiles and runs.
    > Compiling the code using the Standard Library would take a trivial amount
    > of effort.
    >
    >> const double m2k = 1.609;
    >>
    >> int main()
    >> {
    >> double* dp = const_cast<double*>(&m2k);
    >> *dp = 1.892;
    >> return 0;
    >> }
    >>
    >> Thus dp points to a const variable

    >
    > What does the Standard specify it should point to, or is that specified?


    It is specified in [5.2.11/3].


    >> and you attempt to change that const
    >> variable using a dereferenced dp.
    >>
    >> The operating system has presumably stored m2k in a read-only section of
    >> memory, so raises a segmentation fault when you attempt to write to that
    >> memory.

    >
    > As I sated, I understand what happened. I'm just not sure what rule was
    > violated.


    The code has undefined behavior according to [7.1.5.1/4].


    > I guess I go back to slogging my way through the artful prose
    > of the formal arcana of the Standard.



    Best

    Kai-Uwe Bux
     
    Kai-Uwe Bux, Dec 9, 2006
    #7
  8. On 2006-12-09 14:14, Steven T. Hatton wrote:
    > John Carson wrote:
    >
    >> "Steven T. Hatton" <> wrote in message
    >> news:
    >>> I found the example code below, listed in the book described here:
    >>> http://cartan.cas.suffolk.edu/moin/OopDocbookWiki
    >>>
    >>> The result was a bit surprising. I guess it falls into the category
    >>> of "that's what you get for lying". Can the behavior demonstrated be
    >>> explained in standardese? Yes, I know the exact result is "undefined
    >>> behavior". I can see what happened. But what was the actual
    >>> violation?
    >>>
    >>> // Miles are converted to kilometers.
    >>> #include <QTextStream>
    >>>
    >>> QTextStream cin(stdin, QIODevice::ReadOnly);
    >>> QTextStream cout(stdout, QIODevice::WriteOnly);
    >>> QTextStream cerr(stderr, QIODevice::WriteOnly);
    >>>
    >>> const double m2k = 1.609; // conversion constant
    >>>
    >>> inline double mi2km(int miles) {
    >>> return (miles * m2k);
    >>> }
    >>>
    >>> int main() {
    >>> int miles;
    >>> double kilometers;
    >>> cout << "Enter distance in miles: " << flush;
    >>> cin >> miles ;
    >>> kilometers = mi2km(miles);
    >>> cout << "This is approximately "
    >>> << static_cast<int>(kilometers)
    >>> << "km."<< endl;
    >>> cout << "Without the cast, kilometers = "
    >>> << kilometers << endl;
    >>> double* dp = const_cast<double*>(&m2k);
    >>> cout << "m2k: " << m2k << endl;
    >>> cout << "&m2k: " << &m2k << " dp: " << dp << endl;
    >>> cout << "*dp: " << *dp << endl;
    >>> *dp = 1.892; /* What are we attempting to do here?*/
    >>> cout << "Can we reach this statement? " << endl;
    >>> return 0;
    >>> }
    >>>
    >>> /*OUT
    >>> Enter distance in miles: 23
    >>> This is approximately 37km.
    >>> Without the cast, kilometers = 37.007
    >>> m2k: 1.609
    >>> &m2k: 0x8049048 dp: 0x8049048
    >>> *dp: 1.609
    >>> Segmentation fault
    >>> */

    >>
    >> Deleting the irrelevant, you have:

    >
    > It's often nice to have something that actually compiles and runs.
    > Compiling the code using the Standard Library would take a trivial amount
    > of effort.
    >
    >> const double m2k = 1.609;
    >>
    >> int main()
    >> {
    >> double* dp = const_cast<double*>(&m2k);
    >> *dp = 1.892;
    >> return 0;
    >> }
    >>
    >> Thus dp points to a const variable

    >
    > What does the Standard specify it should point to, or is that specified?


    It should point to the const double m2k.

    >> and you attempt to change that const
    >> variable using a dereferenced dp.
    >>
    >> The operating system has presumably stored m2k in a read-only section of
    >> memory, so raises a segmentation fault when you attempt to write to that
    >> memory.

    >
    > As I sated, I understand what happened. I'm just not sure what rule was
    > violated. I guess I go back to slogging my way through the artful prose of
    > the formal arcana of the Standard.


    The violation is trying to change the value of a const. On your system
    this happens to result in a segmentation fault, but there are systems
    and situations where it won't.

    --
    Erik Wikström
     
    =?ISO-8859-1?Q?Erik_Wikstr=F6m?=, Dec 9, 2006
    #8
  9. kwikius wrote:

    > Steven T. Hatton wrote:
    >
    >> What does the Standard specify it should point to, or is that specified?

    >
    > The only time you can use const_cast on some object reference is when
    > you *know* that the real object is not const. Any const cast on a
    > physically const object results in undefined behaviour. The better
    > option on stuff you *own* is to use mutable:


    My inclination is to try and figure out what I'm doing wrong, and fix it.
    I've come across a couple places recently where experts "Josuttis,
    Vandevoorde, Blanchette, Summerfield, etc." have used const_cast<> and
    defended their choice. Nonetheless...

    > That is my understanding
    > anyway:
    >
    > struct my{
    > private:
    > int n;
    > public:
    > my():n(1),y(2){}
    > // mod is declared as a const function
    > // but maybe want to keep internal count
    > void mod1()const
    > {
    > // dodgy If someone declares a const my
    > my& mm = const_cast<my&>(*this);
    > ++mm.n;
    > }
    > private:
    > mutable int y;
    > public:
    > void mod2()const
    > { // always ok
    > ++y;
    > }
    > };
    >
    > int main()
    > {
    > my x;
    > x.mod1();
    > x.mod2();
    > }


    I know what Stroustrup had to say about mutable. He thinks it is almost
    always a bad idea because it defeats the purpose of const. But the same
    goes for const_cast only more so.

    Here's my hack on the subsequent example from
    http://cartan.cas.suffolk.edu/moin/OopDocbookWiki

    #include <iostream>
    using namespace std;

    void el() {
    const int L = 99;
    int * pL = const_cast<int*>(&L);
    *pL = 101;
    cout << L << '\t' << &L << endl;
    cout << *pL << '\t' << pL << endl;
    }

    void em() {
    const int M = 29;
    int * pM = const_cast<int*>(&M);
    *pM = 66;
    cout << M << '\t' << &M << endl;
    cout << *pM << '\t' << pM << endl;
    }

    const int N = 22;
    void en() {

    int * pN = const_cast<int*>(&N);
    *pN = 33;
    cout << N << '\t' << &N << endl;
    cout << *pN << '\t' << pN << endl;
    }

    int main() {
    el();
    em();
    en();
    }
    /*
    Sat Dec 09 09:06:25:> c++ -o cc1 constcast1.cpp
    hattons@ljosalfr:~/code/c++/ezust/src/casts/
    Sat Dec 09 09:06:46:> ./cc1
    99 0xbfc2ccb0
    101 0xbfc2ccb0
    29 0xbfc2ccb0
    66 0xbfc2ccb0
    Segmentation fault

    */

    The authors are saying that[*] "const int is in stack storage class". I
    believe that is old-timer talk meaning 'automatic variable' but I'm not
    sure. I have a couple of observations about the code above, and the result
    of executing it. The addresses of all the variables which were printed
    prior to the segfault are the same. The segfault happened when the
    variable was placed at global scope. If nothing else, it shows that
    undefined behavior is undefined.

    [*]If I understand correctly.
    --
    NOUN:1. Money or property bequeathed to another by will. 2. Something handed
    down from an ancestor or a predecessor or from the past: a legacy of
    religious freedom. ETYMOLOGY: MidE legacie, office of a deputy, from OF,
    from ML legatia, from L legare, to depute, bequeath. www.bartleby.com/61/
     
    Steven T. Hatton, Dec 9, 2006
    #9
  10. Steven T. Hatton

    kwikius Guest

    Steven T. Hatton wrote:

    > Here's my hack on the subsequent example from
    > http://cartan.cas.suffolk.edu/moin/OopDocbookWiki



    >
    > #include <iostream>
    > using namespace std;
    >
    > void el() {
    > const int L = 99;
    > int * pL = const_cast<int*>(&L); // use pL and its undefined
    > *pL = 101; //undefined behaviour
    > cout << L << '\t' << &L << endl;
    > cout << *pL << '\t' << pL << endl;
    > }
    >
    > void em() {
    > const int M = 29;
    > int * pM = const_cast<int*>(&M); // same applies
    > *pM = 66; //undefined behaviour
    > cout << M << '\t' << &M << endl;
    > cout << *pM << '\t' << pM << endl;
    > }
    >
    > const int N = 22;
    > void en() {
    >
    > int * pN = const_cast<int*>(&N); // and here
    > *pN = 33; //undefined behaviour
    > cout << N << '\t' << &N << endl;
    > cout << *pN << '\t' << pN << endl;
    > }


    All undefined . The only time you can use const_cast is if you know
    something is not but looks like it is:


    // object pointed by p is 'logically const'
    int f( const int & p)
    {
    int & pp = const_cast<int&>(p);
    ++pp; // behaviour here dependent on whether
    // object referenced by pp is "physically const" or not
    // if object is really const... undefined behaviour

    return pp;
    }

    int main()
    {
    int x=0;
    f(x); // OK... x is not really const

    const int y =0;
    f(y); // Bad.. y Is really const ...undefined behaviour
    }

    regards
    Andy Little
     
    kwikius, Dec 9, 2006
    #10
  11. Steven T. Hatton

    kwikius Guest

    Steven T. Hatton wrote:

    > The authors are saying that[*] "const int is in stack storage class". I
    > believe that is old-timer talk meaning 'automatic variable' but I'm not
    > sure. I have a couple of observations about the code above, and the result
    > of executing it. The addresses of all the variables which were printed
    > prior to the segfault are the same. The segfault happened when the
    > variable was placed at global scope. If nothing else, it shows that
    > undefined behavior is undefined.


    Compiler writers will take any opportunity they can for optimsiation.
    If they are allowed to not provide any storage for a const then they
    will try not to do so if its within the rules!. The better the compiler
    the more likely it is.

    regards
    Andy Little
     
    kwikius, Dec 9, 2006
    #11
  12. Steven T. Hatton

    kwikius Guest

    Steven T. Hatton wrote:

    > I know what Stroustrup had to say about mutable. He thinks it is almost
    > always a bad idea because it defeats the purpose of const. But the same
    > goes for const_cast only more so.


    They are different because mutable doesnt cause undefined behaviour,
    whereas const_cast is practically asking for it.
    Mutable is safe whereas const is not, but it probably means that big
    opportunities for optimisation are thrown away. I have used it once
    IIRC, when I should probably have changed the design.

    regards
    Andy Little
     
    kwikius, Dec 9, 2006
    #12
  13. Kai-Uwe Bux wrote:

    > Steven T. Hatton wrote:
    >
    >> John Carson wrote:
    >>
    >>> "Steven T. Hatton" <> wrote in message
    >>> news:
    >>>> I found the example code below, listed in the book described here:
    >>>> http://cartan.cas.suffolk.edu/moin/OopDocbookWiki
    >>>>
    >>>> The result was a bit surprising. I guess it falls into the category
    >>>> of "that's what you get for lying". Can the behavior demonstrated be
    >>>> explained in standardese? Yes, I know the exact result is "undefined
    >>>> behavior". I can see what happened. But what was the actual
    >>>> violation?
    >>>>
    >>>> // Miles are converted to kilometers.
    >>>> #include <QTextStream>
    >>>>
    >>>> QTextStream cin(stdin, QIODevice::ReadOnly);
    >>>> QTextStream cout(stdout, QIODevice::WriteOnly);
    >>>> QTextStream cerr(stderr, QIODevice::WriteOnly);
    >>>>
    >>>> const double m2k = 1.609; // conversion constant
    >>>>
    >>>> inline double mi2km(int miles) {
    >>>> return (miles * m2k);
    >>>> }
    >>>>
    >>>> int main() {
    >>>> int miles;
    >>>> double kilometers;
    >>>> cout << "Enter distance in miles: " << flush;
    >>>> cin >> miles ;
    >>>> kilometers = mi2km(miles);
    >>>> cout << "This is approximately "
    >>>> << static_cast<int>(kilometers)
    >>>> << "km."<< endl;
    >>>> cout << "Without the cast, kilometers = "
    >>>> << kilometers << endl;
    >>>> double* dp = const_cast<double*>(&m2k);
    >>>> cout << "m2k: " << m2k << endl;
    >>>> cout << "&m2k: " << &m2k << " dp: " << dp << endl;
    >>>> cout << "*dp: " << *dp << endl;
    >>>> *dp = 1.892; /* What are we attempting to do here?*/
    >>>> cout << "Can we reach this statement? " << endl;
    >>>> return 0;
    >>>> }
    >>>>
    >>>> /*OUT
    >>>> Enter distance in miles: 23
    >>>> This is approximately 37km.
    >>>> Without the cast, kilometers = 37.007
    >>>> m2k: 1.609
    >>>> &m2k: 0x8049048 dp: 0x8049048
    >>>> *dp: 1.609
    >>>> Segmentation fault
    >>>> */
    >>>
    >>> Deleting the irrelevant, you have:

    >>
    >> It's often nice to have something that actually compiles and runs.
    >> Compiling the code using the Standard Library would take a trivial amount
    >> of effort.
    >>
    >>> const double m2k = 1.609;
    >>>
    >>> int main()
    >>> {
    >>> double* dp = const_cast<double*>(&m2k);
    >>> *dp = 1.892;
    >>> return 0;
    >>> }
    >>>
    >>> Thus dp points to a const variable

    >>
    >> What does the Standard specify it should point to, or is that specified?

    >
    > It is specified in [5.2.11/3].


    "For two pointer types T1 and T2 where

    T1 is cv1 , 0 pointer to cv1 , 1 pointer to . . . cv1 ,n ? 1 pointer to
    cv1 ,n T

    and

    T2 is cv2 , 0 pointer to cv2 , 1 pointer to . . . cv2 ,n ? 1 pointer to
    cv2 ,n T

    where T is any object type or the void type and where cv1 ,k and cv2 ,k may
    be different cv-qualifications, an rvalue of type T1 may be explicitly
    converted to the type T2 using a const_cast. The result of a pointer
    const_cast refers to the original object."


    >
    >>> and you attempt to change that const
    >>> variable using a dereferenced dp.
    >>>
    >>> The operating system has presumably stored m2k in a read-only section of
    >>> memory, so raises a segmentation fault when you attempt to write to that
    >>> memory.

    >>
    >> As I sated, I understand what happened. I'm just not sure what rule was
    >> violated.

    >
    > The code has undefined behavior according to [7.1.5.1/4].


    "Except that any class member declared mutable (7.1.1) can be modified, any
    attempt to modify a const object during its lifetime (3.8) results in
    undefined behavior."

    So if an object is defined non-const,

    int obj;

    and passed through a const reference

    void foo(const int& cobj){
    //cobj is a const reference to a non-const object
    }

    the object in the body of the function to which it was passed was itself not
    declared const. (cobj is a const reference to non-const obj) But the author
    of a function who casts away constness has no a priori means of knowing
    whether what will be passed will be const.

    I guess all of the above means I can't complain about anything that happens
    after *pL = 101;

    void el() {
    const int L = 99;
    int * pL = const_cast<int*>(&L);
    *pL = 101;
    cout << L << '\t' << &L << endl;
    cout << *pL << '\t' << pL << endl;
    }

    >> I guess I go back to slogging my way through the artful prose
    >> of the formal arcana of the Standard.


    Thanks!
    --
    NOUN:1. Money or property bequeathed to another by will. 2. Something handed
    down from an ancestor or a predecessor or from the past: a legacy of
    religious freedom. ETYMOLOGY: MidE legacie, office of a deputy, from OF,
    from ML legatia, from L legare, to depute, bequeath. www.bartleby.com/61/
     
    Steven T. Hatton, Dec 9, 2006
    #13
  14. Steven T. Hatton

    Andre Kostur Guest

    "kwikius" <> wrote in
    news::

    >
    > Steven T. Hatton wrote:
    >
    >> What does the Standard specify it should point to, or is that specified?

    >
    > The only time you can use const_cast on some object reference is when
    > you *know* that the real object is not const. Any const cast on a
    > physically const object results in undefined behaviour. The better
    > option on stuff you *own* is to use mutable: That is my understanding
    > anyway:


    Uh, not true. Casting away the constness of the physically const object is
    fine. It's when one attempts to then modify the object is when Undefined
    Behaviour occurs.
     
    Andre Kostur, Dec 9, 2006
    #14
  15. Steven T. Hatton

    Kai-Uwe Bux Guest

    Steven T. Hatton wrote:

    > Kai-Uwe Bux wrote:

    [snip]
    >> The code has undefined behavior according to [7.1.5.1/4].

    >
    > "Except that any class member declared mutable (7.1.1) can be modified,
    > any attempt to modify a const object during its lifetime (3.8) results in
    > undefined behavior."
    >
    > So if an object is defined non-const,
    >
    > int obj;
    >
    > and passed through a const reference
    >
    > void foo(const int& cobj){
    > //cobj is a const reference to a non-const object
    > }
    >
    > the object in the body of the function to which it was passed was itself
    > not declared const. (cobj is a const reference to non-const obj) But the
    > author of a function who casts away constness has no a priori means of
    > knowing whether what will be passed will be const.


    It's even worse: because of 8.3.5/5 the programmer cannot even be sure that
    the passed parameter object binds directly to the const reference; a
    temporary copy could be created. Once you access this through const_cast,
    you may just modify the temporary.

    There is, as far as I can see, only one valid use of const_cast: you can use
    it to define a member function returning a non-const reference / pointer to
    non-const exposing a member in terms of a const member function that
    exposes const access to that member. This can avoid code duplication, e.g.,
    when implementing smart pointers.


    [snip]


    Best

    Kai-Uwe Bux
     
    Kai-Uwe Bux, Dec 9, 2006
    #15
  16. Steven T. Hatton

    IR Guest

    Andre Kostur wrote:
    > Uh, not true. Casting away the constness of the physically const
    > object is fine. It's when one attempts to then modify the object
    > is when Undefined Behaviour occurs.


    Of course, you are right. But what's the point of casting constness
    away if you don't modify the object? (note that I'm not including
    poorly written libraries or APIs that are not const-correct)

    This is the very same problem as reinterpret_cast: you can cast
    anything to whatever you like as long as you cast it back to the
    original type *before* trying to access the object.

    IMO this is bad programming practice and should be avoided by any
    means (unless you really have to cope with poorly written external
    libraries).


    Cheers,
    --
    IR
     
    IR, Dec 9, 2006
    #16
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Amir
    Replies:
    3
    Views:
    627
  2. nc
    Replies:
    1
    Views:
    530
    nice.guy.nige
    Feb 3, 2005
  3. Replies:
    2
    Views:
    371
  4. Jeannie
    Replies:
    15
    Views:
    919
    Jeannie
    Aug 30, 2005
  5. G
    Replies:
    3
    Views:
    468
    Sylvester Hesp
    Jan 8, 2007
Loading...

Share This Page