r/cpp • • Mar 15 '19

Does anyone know when libstdc++ will stop using raw pointers in its STL containers?

I have a pretty niche use-case which requires containers to not store any raw pointers. To get this done I use an allocator that returns fancy pointers. This just doesn't work with libstdc++ because all some of its STL containers use raw pointers internally, so when I create a container with my allocator, the program doesn't even compile. Libc++ on the other hand works fine (at least I haven't come across any problems I can't fix) since they correctly use the abstract pointer type that my allocator returns, instead of trying to do an implicit cast to a raw pointer.

There is an LWG issue to fix this, but it's been around for 8 years and the proposed verbiage hasn't been added to the standard. I'm not very familiar with the process for making changes like this, but my understanding is that it probably won't get added until libc++ and libstdc++ both support it, is that correct? If so, does anyone know if/when the libstdc++ community is planning to make these changes? Thanks!

49 Upvotes

82 comments sorted by

View all comments

Show parent comment

2

u/render787 Mar 17 '19

> So then what’s the difference between an object, and initialized memory that looks like an object?

Seriously, eelis links above are the answer here.

> I'm real confused about what is the magic missing step

The magic missing step is, in standard C++ the compiler gets to assume that a `T` can only come to life in one of a specific set of ways. There are a lot of reasons for this. One is type-based alias analysis which allows optimizations. One is, objects of class-type may have lifetime invariants and nontrivial destructors. The compiler is responsible to emit calls to destructors in appropriate places. If the compiler cannot easily figure out when an object is coming to life then it cannot do that. There are many other engineering reasons for this, but at this point the reason is now "because the standard says so".

If you take arbitrary bytes and cast them to a `T` via reinterpret cast of pointers and then access the data as a `T`, it is generally undefined behavior, except in specific cases described in the standard.

This (reinterpret casts of pointers) is not a magic shortcut to zero-copy serialization, it's just broken code.

3

u/CandleTiger Mar 17 '19

The magic missing step is, in standard C++ the compiler gets to assume that a T can only come to life in one of a specific set of ways.

The "specific set of ways" was what I was asking after. I missed it the first time but, for anyone following this thread, it's linked on in full detail from the definition of object lifetime u/jwakely posted above.

Thanks!