On 12/20, Peter Zijlstra wrote:
On Fri, Dec 20, 2013 at 08:01:57PM +0100, Oleg Nesterov wrote:
> The only problem is that
>
> #define ASSIGN_CONST(l, r) (*(typeof(r) *)&(l) = (r))
>
> obviously can't work in this case ;) We need something more clever.
Hmm indeed, C++ has both the const_cast<>() thingy and the template
system is powerful enough to actually implement const_cast<>() inside
the language.
But I cannot find anything useful for C. Your attempt to use the rvalue
type to hopefully obtain a const-less lvalue type is clever, but does
indeed fail where the rvalue is const too.
Yes.
We can probably do
#define ASSIGN_CONST(l, r) ({ \
typeof (l) const r__ = (r); \
memcpy((void *)&(l), &(r__), sizeof(l)); \
(l); \
})
gcc can actually avoid a temporary if you do
ASSIGN_CONST(tsk->pid, leader->pid);
but this doesn't look very nice and assumes __builtin_memcpy().
So, how about
#define CONST_CAST(type, lval) \
(*({ \
(void)((type *)0 == &(lval)); \
(type *)&(lval); \
})) \
?
de_thread/copy_process can do
CONST_CAST(pid_t, tsk->pid) = leader->pid;
and if "type" is wrong we have a warning.
Oleg.