logoalt Hacker News

nananana9today at 2:22 PM6 repliesview on HN

  template <typename T>
  struct Slice {
      T* data = nullptr;
      size_t size = nullptr;

      T& operator[](size_t index) {
        if (index >= size) crash_the_program();
        return data[index];
      }
  };

If you're considering this extension, just use C++ and 5 lines of standard, portable, no-weird-annotations code instead.

Replies

ueckertoday at 2:56 PM

Or just do it in C.

  #define span(T) struct span_##T { size_t len; T *data; }
  #define span_access(T, x, i) (*({              \
    span(T) *_v = (x);                           \
    auto _i = (i);                               \
    if (((size_t)_i) >= _v->len) abort();        \
    &_v->data[_i];                               \
  }))
https://godbolt.org/z/TvxseshGc
show 2 replies
zmodemtoday at 2:53 PM

The extension is for hardening legacy C code without breaking ABI.

pjmlptoday at 2:33 PM

Even better, starting with C++26, and considered to be done with DR for previous versions, hardned runtimes now have a portable way to be configured across compilers, instead of each having their own approach.

However, you still need something like -fbounds-safety in C++, due to the copy-paste compatibility with C, and too many people writing Orthodox C++, C with Classes, Better C, kind of code, that we cannot get rid of.

show 2 replies
wat10000today at 2:53 PM

You should tell the LLVM folks, I guess they didn't know about this.

osmsuckstoday at 5:27 PM

  size_t size = nullptr;
wat
baqtoday at 2:23 PM

and if you write directly in assembly you don't even need a C++ compiler

show 1 reply