This is the mail archive of the gcc-patches@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: [PATCH] PR c++/80544 strip cv-quals from cast results


On 25/05/17 16:56 +0200, Jakub Jelinek wrote:
On Thu, May 25, 2017 at 03:52:47PM +0100, Jonathan Wakely wrote:
I'd probably write that like this instead:

void
foo (const void *p)
{
 typedef const int* ptr_type;
 ptr_type const q = (ptr_type) p;
 ptr_type const r = (ptr_type) p;
 (void) q;
 (void) r;
}

It names the type only once, not twice as in your example, and doesn't
need to use typeof to refer to that type again.

That was over-simplified, I meant cases where you actually don't know the
exact type, just use typeof to create a variable of such a type and
then want to cast something to that type.

The most obvious case I can think of where you don't know the type
would be the result of some expression (maybe involving overloaded
operators, or a call to an overloaded function).  In that case:

 typeof (expr) const q = (typeof (expr)) p;

Again, add the const to the variable definition, but not the cast.

or using a typedef again for clarity and to avoid the repetition:

 typedef typeof (expr) the_type;
 the_type const q = (the_type) p;

If the result of the expression is a scalar type then it won't be
const-qualified, so the_type isn't either, and the cast won't warn.

If the result of the expression is a class-type then it can be
const-qualified, and so the_type is also const-qualified, but the
warning isn't issued in such case.

All the realistic case I can think of expr won't be simply a variable
(because if you have a variable then it was already declared with some
type and you can refer to that type directly) so the original problem
where typeof(q) deduces a const-qualified type won't happen.

template<typename T> void f (const T& t, const void* p) {
 // no need for typeof(t) because we can just use T
 T* const q = (T*)p;
 T* const r = (T*)p;
}

There's this case, which will warn if the type is a pointer or other
scalar:

 auto const q = some_function (p);
 typeof (q) r = (typeof (q)) p

But what you really care about is typeof (some_function (p)) not
typeof (q), which is just the 'expr' case above:

 typedef typeof (some_function(p)) ptr_type;
 ptr_type const q = some_function (p);
 ptr_type const r = (ptr_type)p;

The warning is avoidable by using typeof on the expression that
determines the type, not on a variable that has a const-qualified
version of the type.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]