CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Jan 2004
    Location
    Düsseldorf, Germany
    Posts
    2,401

    Question const_cast's (again)

    Some of the previous threads about const_casts have left me wondering about something. So I wrote the following little test program, the output of which surprised me a little.

    Code:
    #include <iostream>
    
    void increment( int& n )
    {
     ++n;
    }
    
    int main()
    {
     int i = 1;
     std::cout << i << " - ";
     increment( i );
     std::cout << i << "\n";
    
     const int j = 1;
     std::cout << j << " - ";
     // The following does not compile
     // int l = const_cast<int>( j );
     int * pj = const_cast<int*>( &j );
     increment( *pj );
     std::cout << j << "\n\n";
     return 0;
    }
    Output:
    1 - 2
    1 - 1

    Does const_cast create a copy of the object? Or is this what "undefined behavior" stands for?

    Let me know if other compilers (I'm using g++) create different results.

  2. #2
    Join Date
    Feb 2004
    Location
    Garden City | Silicon Valley .. etc, Bangalore
    Posts
    15

    const_cast

    Hello ,

    The out put u can't say wht exactly it will come tht behavoir is called Undefined behavior
    sivakumar

  3. #3
    Join Date
    Mar 2002
    Location
    California
    Posts
    1,582

    Re: const_cast's (again)

    I'll try answering this with entire words and complete sentences.

    Originally posted by treuss
    Does const_cast create a copy of the object? Or is this what "undefined behavior" stands for?

    Let me know if other compilers (I'm using g++) create different results.
    This is a completely invalid thing to do. A const POD item will not likely exist in normal variable space. At best, you are modifying non-modifyable memory. Even worse, a compiler could do away with this definition completely so that it takes up 0 memory.

    Of course, it's compiler dependent. The behavior is indeed undefined.

    Jeff

  4. #4
    Join Date
    Dec 2003
    Posts
    99
    Hi,
    To be precise the problem is in the statement
    Code:
                     increment( *pj );
    You are passing some temporary variable to the increment function.

    And n (in increment) would now be an alias to this variable and not *pj.

    Thus this seems to me as a defined behaviour as far as value of *pj is concerned, since there is no reason that it should change.

    Regards,

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured