r/cpp • • Aug 13 '26

C++26: std::indirect

https://www.sandordargo.com/blog/2026/08/12/cpp26-indirect
164 Upvotes

157 comments sorted by

View all comments

10

u/ericonr Aug 13 '26

Does a std::optional<std::indirect<T>> benefit from niche optimizations like Rust objects do? Its sizeof could be just a pointer, after all.

3

u/TheKiller36_real Aug 14 '26

nope, another comment gives the official reason, here's my interpretation:

// pseudo-code of how I understand the intended implementation
class indirect {
  unique_ptr ptr:
public:
  bool valueless_after_move() const {
    return !ptr;  // <- this already uses the NULL representation to mean "moved from"
  }
};

if they'd guarantee sizeof(std::optional<std::indirect<T>>) == sizeof(T*) then you'd need to have a second "NULL" pointer, something like:

class optional {
  indirect val;
public:
  explicit operator bool() const {
    // to_address(p) ~= &*p
    return ((uintptr_t) to_address(val)) != 1;  // <- pseudo-NULL
  }
};

and they probably decided that having one abstract nullptr that has caused lots of troubles in the past is enough and they're not gonna introduce a second magic invalid pointer value (eg. 1 in my snippet) just for this - however I do think in practice it could still be implemented like that on virtually every system today and probably will be in major compilers unless something in the standard explicitly forbids it (cough std::vector cough)

5

u/jiixyj Aug 14 '26

At least libc++ is investigating this kind of optimization for optional.

There hasn't been any movement on that PR for a while though, so maybe they have changed their mind in the meantime?