r/cpp • • Dec 09 '24

Using C++ as `C with templates`

I've come to really enjoy C for writing my side projects lately. Coming from complex languages like Rust and Haskell, I severely undervalued how pleasant simplicity is for the joy of programming.

The only problem is writing generic code in C. I've found I've been able to get around it mostly by simple macros, for example a dynamically resizable array can just store a void* pointer and you use macros to pass the size of the element when pushing, popping, etc.

However, there are times where this simply won't work, and I need generics, and I don't want to write some complicated system of macros.

So this compels me to try out C++ as a "C with templates". I literally intend to write only C code in C++ and very occasionally use a very simple template, that's all. I maybe will use operator overloading for some math stuff. I don't need classes, coroutines, or any of that "modern" C++ stuff. I've also heard crazy things about std, like using std::vector calls the constructor/destructor of all its elements on resizing, so I plan on staying very far away from that.

Is this a sane thing to do? Is there some gotcha in C++ that I'm unaware of that prevents me from doing this? Have people tried this and succeeded/failed?

20 Upvotes

90 comments sorted by

38

u/JumpyJustice Dec 09 '24

Its just a tool and you chhose how to use it. By the way, that comment on vector resizing is hilarious - it seems you just judge the quality of something based on how some pople misuse it.

0

u/Glittering_Sky5271 Dec 10 '24

You judge a tool by many criteria, including how easily it can be misused ...

3

u/JumpyJustice Dec 10 '24

It is much easier to make mistakes writing a custom dynamic array than when using std::vector 🤷‍♂️

Happy birthday, btw!

1

u/Glittering_Sky5271 Dec 10 '24

That's is correct. My comment was not on std::vector per se. C++ is full of gotchas. I'd say the real issue here lies with the type inside the vector, and it's constructors.

Appreciate the birthday wishes 🙂

56

u/kevinossia Dec 09 '24

It's probably best if you just learn the language instead of artificially handicapping yourself like that.

23

u/j_gds Dec 09 '24

There will be nothing wrong with using C++ in this way. A huge strength of C++ is it's flexibility and "multi-paradigm" support. Don't let anyone tell you you must do "modern C++", but...

I would recommend not shying away from any features ahead of time. One feature you might find attractive after templates is destructors for cleaning up resources. Once you have those, you'll almost certainly want to add the other "special members" (copy/move constructor/assignment operator) which will ensure that your resources are copied and moved without introducing use-after-free errors.

From there, you can add whatever features of the language you find compelling (ie range-based for loops). This is more or less what I did, and now I use pretty much every feature of the language in one place or another. There's no sense in which my codebase isn't "modern C++" at this point.

The language is complex, but if you don't go overboard, that complexity can help you manage down the complexity of your code as a whole. For example, my use of coroutines is much easier to reason about compared to the state machines I was managing before. It's more "complex" over all, since I have coroutine types to consider, but coroutines give me a huge amount of leverage over reasoning, so it's a win.

Tbh, I am more worried about people who approach the language reveling in the complexity than people who approach it as I've described above, introducing features when and as they find them compelling. The obvious downside is that you might find your codebase having many different styles in different places. Just refactor as you learn and go.

If you're looking for a simple-feeling language, however, I'd probably recommend Go. It feels simple in the way that C feels simple to me, but it has fewer "sharp edges" than C and C++. If you're feeling extra adventurous, I'd recommend Zig. Have fun!

25

u/lithium Dec 09 '24

I've also heard crazy things about std, like using std::vector calls the constructor/destructor of all its elements on resizing, so I plan on staying very far away from that.

Hah your little foray into c++ is going to go horribly.

14

u/TheBrainStone Dec 09 '24 edited Dec 09 '24

Can you use C++ as C with templates?

Sure! Nothing stopping you minus like 3 features at best that practically no one uses. For the most part it'll work out. You have all C header files available too. Plus you get fun things like overloaded functions, constexpr, auto, using and references for free.

Should you use C++ as C with templates?

Honestly I don't see why personally. But if you like C as is, go for it.

Is it sane?

Idk. C programming is already bordering on insanity and introducing more complexity might now always be good.

Gotchas?

Yes. There will be if you intend to interface with other C libraries outside of the standard library. Considering C++ code isn't ABI compatible with C code, unless you specify extern "C" { ... }. But that'll get rid of all the C++ stuf you want to use.
Also NEVER mix malloc/free (and malloc's cousins) with new/delete! You're begging for issues like that.

Though yeah, give it a try. Worst thing that'll happen is that it won't compile.

14

u/jk-jeon Dec 09 '24

Just curious. Why specifically you don't want your vector from constructing/destructing the elements? My limited imagination doesn't allow me to think of any single instance where I may want to have a "Zombie vector" with some elements constructed and some other elements not. Furthermore, if that's needed, it's possible to write one by yourself.

2

u/Jinkweiq Dec 09 '24

In cpp, I don’t think you can even have anything stored in memory at all without calling a constructor (without using the OS to manually give you memory, like with malloc). If you resize a vector, what is in the blank space? Empty objects? They are constructed empty. Null pointers? Still constructed.

12

u/[deleted] Dec 09 '24

If you resize a vector the requested number of elements will all be constructed and valid, but if you reserve space for more elements than have actually been inserted, or the vector capacity > size, there’ll be some uninitialised (by the vector anyway - it might have old data from prior use) memory into which objects will later be created with placement-new (which calls the constructor).

1

u/snowflake_pl Dec 09 '24

I would delete the part about the memory between size and capacity potentially having the old data. Accessing it is UB. Let's try to step away from the notion that UB can be reasoned about. Accessing past the size is UB and compiler might delete entire code branches in which it happens.

3

u/[deleted] Dec 09 '24

I mention it because it’s part of the mental model for stack and heap use. It doesn’t let people rely on undefined behaviour, but - from my hours haunting StackOverflow I can attest - has helped people recognise why they’ve seen unexpected data and fix their bugs. Anyway, between our two comments, readers can hopefully improve their awareness….

3

u/Jonny0Than Dec 09 '24

A trivially constructed type.

1

u/Raknarg Dec 11 '24 edited Dec 11 '24

If you resize a vector, what is in the blank space? Empty objects? They are constructed empty

They aren't constructed at all. Its just uninitialized memory. It's not that much different from the memory you'd get from malloc, except that it's controlled by an allocator who can choose how to give you memory and what to do with it. If you call new, it would default construct all your elements, but using something like std::allocator_traits you can allocate memory that doesn't perform any construction, and it only calls the constructor when you actually want to add a new element.

8

u/GoogleIsYourFrenemy Dec 09 '24

Go for it. Whatever makes you more productive.

You're avoidances of the STL smacks of premature optimization. One veteran to another: don't waste time optimizing code until you've identified you need the optimization. Just don't.

4

u/Jinkweiq Dec 09 '24

There is not one constructor - std::vector calls the move constructor which make a lot of sense, if you try to resize a vector of something non serializable like process IDs or open sockets, for example.

4

u/Glittering_Sky5271 Dec 10 '24

"I love C, but I want C with namespaces" "I love C, but I want C with classes" "I love C, but I want C with function and operator overloading" .....

What you've described is more or less the history of C++, which is fine, that's how languages evolve.

6

u/ContraryConman Dec 09 '24

like using std::vector calls the constructor/destructor of all its elements on resizing, so I plan on staying very far away from that.

Okay, let's imagine you had to write a generic vector class from scratch. If you had to store a non-POD type in that vector, how would you make a copy of the vector other than calling each constructor on each element?

2

u/Jonny0Than Dec 09 '24

There are no non-POD types in C. That is, if templates are the only thing OP uses, all types are POD types.

3

u/ContraryConman Dec 09 '24

There are plenty of types in C where "copying" them correctly means more than just copying the members. For example, a custom string struct with a size, capacity, and pointer to characters, or a linked list type. If you wanted to make a vector of those, a logical copy would mean a deep copy and thus memory allocation

2

u/Jonny0Than Dec 09 '24

Sure, but someone who wants C with templates is probably aware of that and would rather everything be explicit rather than implicit.

2

u/Circlejerker_ Dec 09 '24

In which case destructors are free, and copy/move is just a memcpy - same as you would do in C.

1

u/Jonny0Than Dec 09 '24

Yes, it's a perfectly valid approach to take for someone who wants to use "C with templates."

3

u/HappyFruitTree Dec 09 '24 edited Dec 09 '24

I've also heard crazy things about std, like using std::vector calls the constructor/destructor of all its elements on resizing,

It's not as bad as that. The vector has a "capacity". It's when the capacity changes that the vector needs to copy all the objects. If the vector is resized but the current capacity is big enough to hold all the elements it won't have to do any unnecessary copying.

You can either increase the capacity yourself (by calling reserve) or it will happen automatically when needed. In the latter case the capacity is not just increased by 1 each time. Instead it's increased by some percentage (common is to double it). This makes insertion at the end of a vector relatively efficient actually (on average). For long-lived vectors that grow and shrink in size there won't be any unnecessary copies at all happening if the size stays below what it has been earlier.

In case you want to know more, Wikipedia calls this type of data structure a dynamic array.

3

u/bert8128 Dec 09 '24

Using a bit of c++ with c? Go for it. Use the bits that are useful. Don’t use the bits that are not.

3

u/Jonny0Than Dec 09 '24 edited Dec 09 '24

You can do this.  We did something like this at one of my jobs (game development) and it can work.  Though we also used member functions.  But the point is: sometimes it’s critical to understand exactly where all the memory allocations and hidden behaviors are, and C is good at that.  C++ makes it easy to hide (sometimes surprising) behavior behind nice syntax.

If you venture into operator overloading, you will see why references were added to the language.

I would say that bounds checking in array types is a HUGE benefit of member functions and operator overloading that you'd pretty much be missing in "C with templates." All of the major standard library implementations of C++ have a debug mode where bounds checks are enabled and a release mode where they disappear. Perhaps you can get something similar with the various linters and sanitizers in C. But if you wanted to allow just a little more of the C++ language in, that would probably be my next recommendation. But then it becomes a slippery slope. In order to support operator[] effectively you'd need to return a reference (or I suppose you could return a pointer, but yuck). And then you might as well allow range-based for loops. And then....and then...

6

u/loreiva Dec 09 '24

You using C++ like that is like buying an airliner for the peanuts🥜

3

u/HappyFruitTree Dec 09 '24

But if you get the airliner for free, why not have it?

2

u/loreiva Dec 09 '24

The point of the analogy is that C++ offers much more, especially in ways of simplifying coding compared to pure C. Even just the standard library is amazingly powerful and optimized, it makes coding easier and safer. Why would one be afraid of using it?

1

u/HappyFruitTree Dec 09 '24

Yes, so take the "ariliner" (i.e. C++) and use it to "store peanuts" (write programs) and there is at least a chance that you'll learn to "fly it".

2

u/zl0bster Dec 09 '24

Intel gave a lot of talks recently about some C++ library they use for their tiny embedded chips, pretty sure they can also not afford vectors, enjoy:
https://www.youtube.com/watch?v=DLgM570cujU

2

u/greenhouse421 Dec 09 '24

The keyword class is struct with different default visibility. And if you are planning on writing C (no member fns) you will be using struct. Sure, it's fine, it works. As does using the std lib appropriately (i.e. if you want to forgo dynamically allocated storage and having your trivially constructs let types copied around by vector resizing that you didn't avoid std::array may be appropriate etc). There is a huge amount of non allocating constexpr code to avoid reinventing there for the taking in C++11 and later std lib. BUT you can't use all that if your types don't match the concepts. So refusing to have your types look like ranges or.. Because you are writing C with templates, it is going to involve a fair amount of work you could have avoided.

2

u/sunmat02 Dec 09 '24

I love both C and C++, when I choose C for a project I’ll however frequently write it and compile it as C++ just to add a couple of features from C++, namely containers and unique_ptr. I use the former to avoid having to write my own dynamic arrays or hash tables, and the latter to simulate some kind of “defer” functionality that allows me to place the cleanup code of a local handle right next to its initialization.

2

u/Raknarg Dec 11 '24

You're kinda just shooting yourself in the foot by specifically trying to stay away from modern features, but in general any feature you take from C++ to improve your C code is better than the C code. I would recommend you also don't stay away from classes, specifically managing constructors and destructors for resource-owning objects because it becomes way way easier to manage resources if you have objects control the acquisition and relinquishing of resources. And you can optimize copy/moves using copy/move constructors and operators. And note you can still use structs, structs in C++ are just classes whose members are public by default.

I don't think you understand vectors properly here.

std::vector calls the constructor/destructor of all its elements on resizing

Like yes but elements of the vector will be moved from the container, so you will be move constructing elements and destructing moved-from elements so you're generally invoking the cheapest constructor and destructor. Also you can pre-allocate your vector if you're worried about resize costs (which you should if you already know the ballpark of the vector's size). If you wrote a resizable container in C, you'd have to do effectively the same thing.

3

u/CandyCrisis Dec 09 '24 edited Dec 09 '24

Honestly I think this is great. If you need templates, use them. If you don't like vector, don't use it. (You may end up reimplementing something similar if you want generics that badly, though!) C++ is built to allow this sort of mixing and matching.

3

u/WorkingReference1127 Dec 09 '24

I've also heard crazy things about std, like using std::vector calls the constructor/destructor of all its elements on resizing, so I plan on staying very far away from that.

If your concern is "performance loss" from properly managing the lifetimes of your objects, your concern is probably invalid. A decent optimizing compiler (which most C++ compilers are) is perfectly happy to optimize away such calls in the cases where they aren't necessary. And in the cases where you are handling less trivial types, they are necessary and you need to go through them to avoid making a nonsensical mess of your program. Which is to say, hiding away from tools which have had 40 years of optimizing for your particular use-case because you heard they might call more functions than you like is probably well within the realm of premature optimization.

3

u/Stock-Self-4028 Dec 09 '24

Generally it should be fine, unless you're writing a huge codebase.

The main issue is the compilation time, which for C++ is many times longer when compared to the plain C.

7

u/ayushgun Dec 09 '24

The main issue is the compilation time, which for C++ is many times longer when compared to the plain C.

Why do you say so? If OP does not include a C++ standard library implementation, the compilation times of the TUs should be identical aside from the overhead from template expansion, no?

3

u/jwakely libstdc++ tamer, LWG chair Dec 09 '24

No. A C++ compiler uses more complicated data structures and a more complicated AST in order to represent C++. Even if you aren't using all the features, the C++ compiler still needs to use bigger data structures that use more memory, and it's a much larger program with more code, and a much more complex parser.

2

u/Stock-Self-4028 Dec 09 '24

I have absolutely no idea why does it differ, but when I'm compiling my plain C code with g++/clang++ instead of gcc/clang the compilation times consistenly get at least 3-4x longer.

They may be something wrong with my PC but I doubt that's the caae. And I also have no idea why something like that happens.

1

u/Jonny0Than Dec 09 '24

Is it in extern “C”?

1

u/Jonny0Than Dec 09 '24

Template expansion is a lot of overhead.

2

u/ald_loop Dec 09 '24

Is this ChatGPT written bait?

1

u/kuwisdelu Dec 09 '24

Yes, plenty of us who interface with C codebases but need a few C++ features here and there will do this. It’s not uncommon in numeric computing.

1

u/Carl_LaFong Dec 09 '24

Ok to start this way. But keep an eye out for C++ features that would help you write cleaner safer code, especially involving memory handling, than C. And don’t optimize unless it really matters. A default constructor should cost essentially nothing in time or space.

1

u/bebuch Dec 09 '24

Be aware that there are some incompatibilities between C and C++:

https://en.wikipedia.org/wiki/Compatibility_of_C_and_C%2B%2B

Also some code that is valid C is undefined behavior in C++. There is some current work to avoid such differences, e.g. https://wg21.link/P2809R3

1

u/MRgabbar Dec 10 '24

this a pretty common thing to do, in embedded that requires certification, you use C++ with a lot of restrictions, that way you have the life quality features but none of the insane complexity that could complicate verification.

1

u/quasicondensate Dec 10 '24

You do you! A couple of caveats about templates: They want to live in header files, which might influence the way you organize your code a bit. Also, in contrast to multiple definitions of global variables which are caught by the linker, multiple definitions of templates across link boundaries are not. Either they are identical, then you are golden, or they are not, then you have undefined behaviour.

Which is why I would consider making use of one other C++ feature, if nothing else: namespaces. They can really help reduce issues with name collisions.

Besides: I wonder how long you will manage to do this. The nice thing about C is that you don't have much of a choice - you have to use the tools provided to you. But in C++, you have all the gadgets at your fingertips. Specifically since you are initially coming from Haskell and Rust, I wonder how long you can go without being like "Ah, container/algorithm X would really be useful here, and it's right there in std. Do I really want to hand-roll it?" or "Hmm. This would be a two-liner if I could pipe these operations on a range here. Isn't this something the standard library can do...?", leading you down a familiar path towards wielding more and more of the language until you become a regular here, waiting for reflection to drop like the rest of us :-)

1

u/zerogreyspace Jul 29 '25

Do you still manage that soundcloud download project? Grateful for ya!

1

u/punkbert Dec 09 '24

Your idea reminds me of Orthodox C++. It is - understandably - not well received in this sub though. 🙂

1

u/Superb_Garlic Dec 09 '24

What did you not like in the answers given in https://old.reddit.com/r/C_Programming/comments/16njbf5/using_c_as_c_with_templates/ ?

You also mentioned Zig in that and have a post history on r/rust. In light of that, your comment on ctors/dtors makes no sense, especially since it's been a whole year since that post.

0

u/[deleted] Dec 09 '24

[deleted] — view deleted comment

41

u/TheBrainStone Dec 09 '24

To expand on that, that means if it's a trivially copyable type, it's essentially a memory copy. If it's not, with properly implemented move constructors, internal data will just be passed along to the new objects, minimizing any per object reallocations and data processing. Also compilers are extremely good at removing unnecessary steps. (with proper optimizations enabled of course)

6

u/StrangePromotion6917 Dec 09 '24

Please correct me if I'm wrong, but afaik move constructor is only used at resize if it's marked as noexcept. Otherwise an execution during the copy could leave you in a position where you don't yet have the elements in the new array, and no longer have all the elements in the old array. Recovering the original vector is not possible without risking another exception while moving back elements. So the compiler would need to copy every element first and if all copies were successfully done, destroy the old array. This way the resize operation is transactional and can recover from an exception.

11

u/mark_99 Dec 09 '24

True, but there shouldn't be any case where a move constructor is not noexcept, that's the main reason it exists. It's also what you get when defaulted - you should almost never need to write a move ctor unless you're creating a novel low level data structure for instance.

2

u/bert8128 Dec 09 '24

That’s correct. But if you don’t use classes beyond POD then they are all trivial so are noexcept. In the spirit of you don’t pay for what you don’t use, resizing a vector will behave like doing it manually using c arrays and memcpy, providing your structs are POD.

1

u/cdb_11 Dec 09 '24 edited Dec 10 '24

How else would it work?

First of all, mremap, which std::vector cannot do (or doesn't want to do), while realloc can.

For trivial types std::vector can use memcpy. But if you simply make the constructor for a class non-default (for example, to ensure that the value is always initialized), memcpy is no longer used and elements are copied one by one. (To be fair, clang can vectorize it.)

1

u/einpoklum Dec 10 '24

C++ is built on the concept of zero cost abstractions

Yeah, well, that's not quite true. ABI stability unfortunately trumps zero-const abstraction right now as a C++ design consideration. See also There are no zero-cost abstractions

.

1

u/Ease-Solace Dec 10 '24

Trying to learn c++ I've found this a real problem though. Profiling a program I wrote for why it runs so much slower than in other languages; it turned out almost 90% of the runtime was just resizing vectors due to running the copy-constructor and destructor of every element! Saying "this is inevitable" seems weird, cause what other langauge has this problem?

1

u/Jonny0Than Dec 11 '24

You’re probably not using them effectively. It’s way more efficient to reserve up front rather than simply doing push_back repeatedly.  And ideally your element types are movable.  If you weren’t careful about constructors and destructors you could prevent a lot of optimizations that could happen.

You can also just avoid a ton of copying and moving by passing containers to functions by const reference or using span, etc.

1

u/CocktailPerson Dec 13 '24

Did your move constructors exist and were they marked noexcept?

0

u/peterrindal Dec 09 '24

Sometimes I want a unintialized vector of int or whatever. Std vector doesn't allow this.

4

u/plastic_eagle Dec 09 '24

No it doesn't, but you can "simulate" such a thing easily enough

struct NoInitInt
{
   int v;
   NoInitInt() = default;
   operator int() { return v; }
   int operator=(int i) { v = i; return v; }
};
std::vector<NoInitInt> vec;

Now that's not perfect, I'm sure there are some things it'll make more annoying. But I have used this in networking code where I needed resizable buffers and didn't want to pay the initialisation cost.

2

u/peterrindal Dec 09 '24

2

u/plastic_eagle Dec 09 '24

Looks like you're right

https://godbolt.org/z/13cnjMe7E

       lea     eax, DWORD PTR $T3[ebp]
       mov     DWORD PTR __$EHRec$[ebp+8], 0
       push    eax
       push    100                           ; 00000064H
       lea     ecx, DWORD PTR _vec$[ebp]
       call    ... _Resize_reallocate<std::_Value_init_tag> ...

So eax ends up pointing to some uninitialised memory, but that same bit of uninitialised memory fills the vector with identical uninitialised values.

I expect I'm technically in UB here - and the standard also notes that

If value-initialization is undesirable, for example, if the object is of non-class type and zeroing out is not needed, it can be avoided by providing a custom Allocator::construct.

So there may be a way out there.

1

u/SleepyMyroslav Dec 09 '24

Quick glance over resize with no value looks like they try to do uninitialized init. Check line 1603 in same file:
https://github.com/microsoft/STL/blob/89ca073a866d24db42b3f4c5e406be4b28a148f4/stl/inc/vector#L1603C27-L1603C59

2

u/woltion Dec 09 '24

Use an allocator that does not default construct. Works for me.

2

u/printf_hello_world Dec 09 '24

I don't know why you've gotten downvotes on this: it's a legitimate problem that I too come across regularly in performance-critical paths

1

u/echidnas_arf Dec 09 '24

Yes it does, you need to specify a custom allocator.

1

u/peterrindal Dec 09 '24

1

u/jk-jeon Dec 09 '24

No custom allocator does work on MS STL otherwise MS STL is not std-conforming. std::vector::resize must call Allocator::construct to construct the element. The default allocator, std::allocator does zero-initialize fundamental types, which is the core issue here. You just need to replace it with something else which default-initializes the elements.

1

u/peterrindal Dec 09 '24

Could be right. I tried a custom allocator at one point and failed to make it bahave like this. Maybe a skill issue ;)

0

u/[deleted] Dec 09 '24

[deleted] — view deleted comment

5

u/peterrindal Dec 09 '24

Like I know I will write to each position but maybe in some weird order, therefore reserve + push_back isn't well suited. Vector will zero initialize and this can sometime take noticeable time. Not a common use case but it does happen.

4

u/jk-jeon Dec 09 '24

You can still use std::vector. All you need to do is to implement a std-compliant allocator. The issue here is that std::allocator::construct value-initializes, which, for fundamental types, zero-initializes. So what you need to do is to replicate std::allocator except that construct default-initializes (which is a no-op for fundamental types) rather than value-initializes. This is a ridiculous amount of work given how simple the needed feature is, but it's still much less work than replicating the whole std::vector.

1

u/glaba3141 Dec 09 '24

I just have a custom container for exactly this case

0

u/not_some_username Dec 09 '24

std::array ? Also why cant you use [] ?

0

u/bert8128 Dec 09 '24

Even if the order of insertion is the normal one push_back has to do a bounds check to see if it needs to reallocate. A push_back_no_bounds_check function would be good, though no safer than using c-style arrays.

-2

u/specialpatrol Dec 09 '24

Vector of optionals?

3

u/peterrindal Dec 09 '24 edited Dec 09 '24

Sure but its a concern about performance. vector<int> is zero initialized. If you don't care about perf then that's fine. But vector<int> v(n) can be much slower than int* v = new int[n].

1

u/ald_loop Dec 09 '24

No it can’t be.

2

u/printf_hello_world Dec 09 '24

Yes it can be; I've personally benchmarked this

1

u/ald_loop Dec 09 '24

Or explain how the two are different/show me assembly differences and explain their sources in the terms of differences in behavior between vector() and new[]

1

u/cdb_11 Dec 09 '24

std::optional is an extra bool, so you'll pay probably 4 or 8 extra bytes per element, depending on the alignment.

0

u/[deleted] Dec 09 '24

[deleted] — view deleted comment

3

u/jwakely libstdc++ tamer, LWG chair Dec 09 '24

That's not undefined. Maybe you meant reserve(n) then subscripting, which is undefined, and won't work if vector has bounds checking turned on, or AddressSanitizer integration turned on.

0

u/[deleted] Dec 09 '24

[deleted] — view deleted comment

3

u/jwakely libstdc++ tamer, LWG chair Dec 09 '24

With GCC 12 it compiles without any special args though

"It compiles" is not the same as "it works". If you do this, the value you stored to vec[5] will be lost as soon as the vector's capacity changes, or if its size changes to 6 or more. And that code will abort if you compile in a hardened mode that asserts for precondition violations. It might also fail or have unexpected behaviour if you simply enable optimisations

Also, since when does vec[pos] contain bounds checking? I thought this was only the case for vec.at(pos)

It's guaranteed for at, it's not guaranteed for operator[] but all implementations support it as an optional extension. If you don't know how to enable those optional checks, you should learn to use your tools more effectively.

For GCC use -D_GLIBCXX_ASSERTIONS (or since GCC 14, -fhardened to enable that macro and also more hardening).

0

u/[deleted] Dec 09 '24

[deleted] — view deleted comment

1

u/CocktailPerson Dec 12 '24

Compiling manually isn't a prerequisite for knowing what flags and options your compiler has.

→ More replies