C, still?
C, still?
Posted Sep 21, 2017 15:23 UTC (Thu) by excors (subscriber, #95769)In reply to: C, still? by adobriyan
Parent article: Building the kernel with Clang
"But then one needs to win holy war against allocators returning "void *""
If you mean the problem is just that you need to add explicit casts in a million places, maybe you could avoid that relatively cleanly with:
class autocast {
public:
autocast(void *p) : ptr(p) { }
template<typename T> operator T*() {
return static_cast<T*>(ptr);
}
private:
void *ptr;
};
#define kmalloc(size, flags) autocast(kmalloc(size, flags))
so it can be implicitly cast to any pointer type (with zero runtime cost).
(Hmm, I wonder if you could then extend it to something like:
template<size_t size>
class checked_autocast {
public:
checked_autocast(void *p) : ptr(p) { }
template<typename T> operator T*() {
static_assert(size >= sizeof(T), "allocated size smaller than return type");
return static_cast<T*>(ptr);
}
private:
void *ptr;
};
#define kmalloc(size, flags) \
__builtin_choose_expr( \
__builtin_constant_p(size), \
checked_autocast<size>(kmalloc(size, flags)), \
autocast(kmalloc(size, flags)))
to detect some bugs.)