C++ “conversion loses qualifiers” compile error

后端 未结 2 1545
野性不改
野性不改 2020-12-20 06:35

I ran into an interesting problem while debugging SWIG typemaps today. Anyone care to enlighten me why Visual C++ 2008 throws a \"conversion loses qualifiers\" error when co

相关标签:
2条回答
  • 2020-12-20 06:41

    In following code,

    friend ostream & operator<<(ostream & output, const List& other)
    {
        for(int i=0;i<other.length();i++)
            output << other.getData()[i] << " ";
    
        return output;
    }
    

    to remove compilation error "Conversion loses qualifiers", for parameter "const List& other", I changed both following called methods to const.

    T* getData() const
    {
        return data;
    }
    
    int length() const
    {
        return lSize;
    }
    
    0 讨论(0)
  • 2020-12-20 06:55

    Say you had the following function:

    void test(  const char*& pRef)
    {
        static const char somedata[] = { 'a' ,'b', 'c', '\0'};
        pRef = somedata;
    }
    

    If you passed in a non-const char*, then when test() returned the compiler would have lost the fact that what p is pointing to is const.

    It's essentially the same reason as given in this C++ FAQ Lite question (dealing with pointers-to-pointers rather than pointer references):

    • http://www.parashift.com/c++-faq-lite/const-correctness.html#faq-18.17
    0 讨论(0)
提交回复
热议问题