const TypedeffedIntPointer not equal to const int *

后端 未结 2 475
误落风尘
误落风尘 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: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 
    
    int main()
    {
        const int * cpi = some_func();
    
        std::map const_int_ptr_map;
        const_int_ptr_map.find(cpi); //ok
    
        std::map int_ptr_map;
        int_ptr_map.find(const_cast(cpi)); //ok
    }
    

提交回复
热议问题