const TypedeffedIntPointer not equal to const int *

后端 未结 2 476
误落风尘
误落风尘 2021-01-20 21:47

I have the following C++ code:

typedef int* IntPtr;
const int* cip = new int;
const IntPtr ctip4 = cip;

I compile this with Visual Studio 2

相关标签:
2条回答
  • 2021-01-20 21:50

    const IntPtr is the same as int* const, not const int*.

    That is, it is a const pointer to an int, not a pointer to a const int.

    A solution would be to provide two typedefs:

    typedef int* IntPtr;
    typedef const int* ConstIntPtr;
    

    and use ConstIntPtr when you need a pointer to a const int.

    0 讨论(0)
  • 2021-01-20 21:52

    When you write const IntPtr ctip4, you are declaring a const-pointer-to-int, whereas const int * cip declares a pointer-to-const-int. These are not the same, hence the conversion is impossible.

    You need to change the declaration/initialization of cip to

    int * const cip = new int;
    

    To resolve this issue in your example, you need to either change the key type of the map to const MyType * (whether or not it makes sense depends on your application, but I think that changing a MyType object via a pointer used as key in the map is unlikely), or fall back to const_casting the parameter to find:

    #include <map>
    
    int main()
    {
        const int * cpi = some_func();
    
        std::map<const int *, int> const_int_ptr_map;
        const_int_ptr_map.find(cpi); //ok
    
        std::map<int *, int> int_ptr_map;
        int_ptr_map.find(const_cast<int *>(cpi)); //ok
    }
    
    0 讨论(0)
提交回复
热议问题