Question

I want to define some generic pointer (? but not a void pointer) using this code:

class A
{

template<typename T>
using ptr = T*;

using ubyte = uint8_t;

public:

    const ptr<ubyte>
    getColor1() const {
        return &colors[0];
    }

    const ubyte*
    getColor2() const {
        return &colors[0];
    }


private:

    ubyte colors[4];
};

However, the getColor1() won't compile. What's the difference between this two functions ?

gcc says:

error: invalid conversion from 'const ubyte* {aka const unsigned char*}' to 'A::ptr<unsigned char> {aka unsigned char*}' [-fpermissive]|

Update:

The deleted answer says I could do this:

//option 1
template<typename T>
using const_ptr = const T*;

or

//option 2
const ptr<ubyte>
getColor()  //remove cv-qualifier
{
    return &colors[0];
}

From option1,

It constructs now to const const, what does const const means?

From option2,

Why just removing cv-qualifier makes this compile?

Was it helpful?

Solution

const ptr<ubyte> is the same as const (ubyte *) which is not the same as const ubyte (*). You are trying to return a const pointer to a non-const char, which the compiler won't allow because you've declared the function itself const; all members become const because of that. The compiler won't automatically cast const to non-const without a const_cast.

To make the difference clearer, the first is a const pointer to a non-const char and the second is a non-const pointer to a const char. The first allows the pointed-to characters to change, even though the pointer itself can't change. Since the function was marked as const it can't return anything that would allow its members to be modified.

The best way to fix it:

ptr<const ubyte>
getColor1() const {
    return &colors[0];
}

OTHER TIPS

Because of the syntax of your ptr template, const ptr<ubyte> first makes it a ubyte*, then applies the const, resulting in a ubyte * const, a constant pointer to an ubyte.

In order to return a pointer to a const ubyte, you need to feed a const ubyte into your pointer template, so constness is applied first:

ptr<const ubyte>

1) "what does const const means?"

const T* const pT = new T;

Means const pointer pT - you cannot assign pT to another object; to a const object of type T - you cannot change the object which is pointed by pT.

2) "Why just removing cv-qualifier makes this compile?"

getColor1()

method without const modifier can modify the object. It now returns A::ubyte* which can be converted to a const type such as declared as return type: A::ubyte* const (const ptr< ubyte > )

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top