CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 15 of 20

Threaded View

  1. #17
    Join Date
    Feb 2009
    Posts
    326

    Re: read only alias to a pointer

    Thanks all for all your valuable inputs, it has helped me understand better.

    Thanks JVene, I was able to understand what your program was doing.
    It was an interesting idea, and I certainly didn't think from that angle.
    In the process I learned the conversion operator, never knew that existed. Thanks.

    Just one point, actually with the program (constalias 2nd version), we wouldn't be able to "declare" a read only alias.

    We would be stuck at the same point because we were attempting the following :

    The conversion operator returns the following type:
    const int* const &

    This is done is by returning a variable of the type int*

    so effectively it is equivalent to:
    Code:
    int* p1;
    const int* const & p2 = p1;
    This is exactly where the gcc compiler seems to differ from MSVC.
    And therefore the conversion operator actually returns a temporary address and not the way we intended.
    Hence we get that warning "warning: returning reference to temporary" while compiling.

    The more I look at it the more it seems like a certain compiler bug.
    The reason I say that is because, "const int* const &" is meant to be an alias (besides other restrictions it is supposed to impose such as not allowing int* and int** to be modified). But in gcc it simply isn't an alias !

    the following would work, till gcc bug is reported and gets fixed:

    Code:
    #include<iostream>
    using namespace std;
    
    int main()
    {
        system("clear");
    
        int v1 = 10; 
    
        int* p1 = &v1;
    
        const int* const * pt = &p1;
        const int* const & pa = *pt;
    
        cout << "&v1 = " << &v1 << "\tv1 = " << v1 << endl;
        cout << "&p1 = " << &p1 << "\tp1 = " << p1 << "\t*p1 = " << *p1 << endl;
        cout << "&pa = " << &pa << "\tpa = " << pa << "\t*pa = " << *pa << endl;
            
        return(0);
    }
    As you suggested the same could be implemented in the form of a template class to cater to a generic solution.

    Thanks again, for all your thoughts, much appreciated !!!
    Last edited by Muthuveerappan; June 21st, 2009 at 10:48 PM.

Tags for this Thread

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