I have been using C++ for a long time now, and I don't know how to write an allocator, and I don't see any relevant use-case.
I would gladly read a in-depth article on common, relevant use-case where an allocator would be useful for a beginner. I understand common STL containers, but not allocators.
It seems like allocators are very important and a very large subject, yet I have never used them, which I don't understand how it's possible... although it can be explained easily since I often prefer to used YAGNI or KISS principles, so I don't dive into very specific complex use-cases.
For example, I would see potential relevant use-case:
a simple vector/pool
a vector where I can remove items randomly, except I replace the deleted item with the last item instead of moving the memory segment on the right of the deleted item: I don't even know if that's a potential case for an allocator, or if this pattern has a name.
Are allocators's usefulness exaggerated seen from YAGNI/KISS point of view? Or am I just a poor, uninterested C++ developer?
https://redd.it/1bsi2mj
@r_cpp
std::map makes it impossible to use a memory pool. But why?
I have written a very fast and efficient memory pool allocator and I can't use it. On MSVC, std::map
allocates some kind of header type and a node type, and it's impossible to know which one is which, so I'll end up allocating 1000000 headers when I only need a single one.
Additionally, the allocator interface is a mess. I couldn't get my allocator to work correctly even after using a shared_ptr
for the memory. It got freed before the map was destructed, resulting in a crash.
I ended up writing my own binary tree class.
Why can't the standard types like map
, set
, list
, and queue
have a simple way to use a memory pool? I mean, it's a language that is intended for writing high-performance code (among other things).
I couldn't even find a memory pool with the correct allocator interface on Google. Probably because of rebinding, which is what I struggled with.
https://redd.it/1bsf00i
@r_cpp
Really strange C++20 module symbol visibility/reachability issue (MSVC ICE)
Suppose you have a small C++ module with a simple struct like this:
module;
#include <string>
export module mymodule;
export struct mystruct
{
static constexpr auto message = std::string{"aaa"};
std::string member{};
};
You then import the module and refer to my_struct in user code:
import mymodule;
int main(int argc, char ** argv)
{
auto x = mystruct{};
}
In MSVC this straight up results in internal compiler error. You will not get any other error messages (if you comment out static constexpr
line you will get link time error "LINK : fatal error LNK1000: Internal error during LIB::Search")
Even though I had found ways to circumvent this error, I never really understood what was the root cause of this error. For instance you can change static constexpr
to static inline const
and it will compile just fine. Or you can remove the std::string
member and everything will compile just fine. That's really strange.
Today I was reading recently purchased book called C++20 The Complete Guide (ISBN: 978-3-96730-920-1) and noticed it had chapter on modules. In 16.1.4 it discussed module symbol reachability vs. visibility. It got me thinking... could this error be because user code doesn't know what std::string
is? Sure enough including <string>
in user code fixes the error:
#include <string> // fixes internal compiler/linker errors
import mymodule;
int main(int argc char ** argv)
{
auto x = mystruct{};
}
This error is not limited to just std::string
. In this example you can replace std::string
with any std class that has constexpr constructor for instance std::array
will ICE too. Is this a bug? Is this a feature? I have not tested this on any other compiler other than MSVC (latest and latest preview).
https://redd.it/1bryeod
@r_cpp
How often do you use design pattern?
Hey everyone! I'm currently a CS student and started recently to learn about design patterns (We apply it in Java but I figured since both are object oriented it could apply to cpp as well). I was just curious, how often will I use it? (I'm not planning to write a single line of Java willingly, let alone making it my job, that's why I ask on this sub)
https://redd.it/1brrll4
@r_cpp
Simple, but dangerous
Hope yall can use my code.
https://pastebin.com/G4Ss1hJ8
https://redd.it/1bregpr
@r_cpp
How can I tell C++ that I want to discard a nodiscard value? - The Old New Thing
https://devblogs.microsoft.com/oldnewthing/20240329-00/?p=109592
https://redd.it/1brdoag
@r_cpp
MSVC spectacularly failing to optimize intrinsics
Hi,
I was investigating the recent performance regression of my library for MSVC, and found this.
[https://godbolt.org/z/fo3o934ra](https://godbolt.org/z/fo3o934ra)
For those who are in mobile, here is the code:
#include <cstdint>
#include <intrin.h>
struct uint128 {
std::uint64_t high_;
std::uint64_t low_;
};
uint128 umul128(std::uint64_t x, std::uint64_t y) noexcept {
auto const seemingly_innocuous_lambda = []() -> uint128 {
return{0, 0};
};
if (false) { return seemingly_innocuous_lambda(); }
uint128 result;
result.low_ = _umul128(x, y, &result.high_);
return result;
}
`_umul128` is supposed to compute 128-bit multiplication of the first two 64-bit parameters, and store the high 64-bits into the location pointed by the third parameter, and return the low 64-bits.
The generated assembly is quite... interesting:
sub rsp, 24
mov rax, r8
mul rdx
mov QWORD PTR result$[rsp+8], rax
mov rax, rcx
mov QWORD PTR result$[rsp], rdx
movups xmm0, XMMWORD PTR result$[rsp]
movups XMMWORD PTR [rcx], xmm0
add rsp, 24
ret 0
If I enable `/GS`, then it gets even more interesting. What's particularly funny is that, if I remove the `if (false)` branch, then now it generates what it's supposed to be like. (In reality, `if (false)` is `if (std::is_constant_evaluated())`, so I cannot remove this branch.)
Now to my main point:
1. If MSVC engineers can look at it and fix it soon, then that would be wonderful, thanks!
2. A workaround in this specific case is to remove the lambda and replace it by a normal function. But I am not sure if that will continue to work in a larger context, when the outer function is also inlined into another function, which in itself may contain other lambdas. If possible, I want to know if this workaround will be okay there, and if not what could be a more robust workaround.
Thanks!
https://redd.it/1br2w8m
@r_cpp
How to practice
I learned the basics ig and still advancing through learn c++ and I'm trying to write some code snippets to get used to the syntax and writing some basic applications but they are very basic and now I feel lost like should I start problem solving or learn a framework like qt and start creating applications through it I really dont know
https://redd.it/1bqzpxb
@r_cpp
Reflection Use Cases
Hi all. I am super excited for the new reflection proposal, and love following the buzz around it.
Most of the examples I see are for either serialization or enum to string. While these are awesome, I feel like it is only scratching the surface of what is possible.
What are some other compelling use cases for reflection?
https://redd.it/1bqr8kh
@r_cpp
char type doubt
I have some confusion . char type has 1 byte size .So it can store 256 values . so 0-255 .but this is in ASCII table . I made a char array , wrote some elements like some alphabets ,and some numbers ,and then wanted to print the char array .If we store a number (0-9 ), the char array gets printed . but if i store a bigger number , it shows a compiler error .I am so confused by all this thing .
https://redd.it/1bqod03
@r_cpp
DateTime: easy to use, header only library for handling Date and Time.
Hello friends.
As some of you might know, handling date and time is a tiring process in c++. Unlike some of the other programming languages like Java and C#, the standart library of c++ doesn't give us an easy to use solution. For this reason, I've written my own DateTime class and I hope it will ease the burden on many other fellow c++ coders.
Please feel free to give feedbacks.
https://github.com/Ozan-Deniz/CPlusPlus-DateTime
Important note: Days start from Monday, providing a deviation from the standard Sunday start used in std::chrono.
https://redd.it/1bd0uyh
@r_cpp
Learning materials for mediors
Hi,
I’m a junior C++ developer with 2+ years work experience and also learned C++ at the university in several subjects. I’m applying for a medior level position (also C++). I developed 3D engines and editors until now so I have experience with Computer Graphics. This medior position is in another field (mostly telecommunication, asynchronous programming, etc.) and has attention on more language specific details such as how and why the language works as it does for example in case of virtual methods or memory management or more on. Can you recommend more advanced learning materials for preparing this interview? I have experience with using these concepts but I want to understand these too.
https://redd.it/1bcutgb
@r_cpp
Class template argument deduction (CTAD) and C++ COM wrappers: Initial explorations - The Old New Thing
https://devblogs.microsoft.com/oldnewthing/20240311-00/?p=109521
https://redd.it/1bcqjbu
@r_cpp
Question to Modern C++ experts: Which rules for variable initialization apply in this sample, in which order, and what is the correct result?
I have been programming in C++98 for a long time (doing embedded and industrial automation stuff, which is a rather conservative domain). And I am trying to understand the rules for variable initialization in modern C++ better. Here is an example which I found somewhere on the web, and which I do not understand:
#include <iostream>
struct A {
A(){}
int i;
};
struct B : public A {
int j;
};
int main() {
B b = {};
std::cout << b.i << " " << b.j << std::endl;
}
Apparently (by looking az compiler warnings with -W uninitialized),
b.j is initialized, but b.i is uninitialized (with at least some versions of gcc, and C++11 and perhaps some other standard iterations). Please explain why! (I am not interested in what your particular compiller spits out but in what is the correct and expected result)
- What rules do exactly apply here? Why do they apply in that way / order?
- What is the best way to initialize stuff in Modern C++ ?
https://redd.it/1bcq9n5
@r_cpp
Could the compiler know what is const even if it is not set as const?
I know that setting variables as const where possible in C++ enables some compiler optimizations that can make the program run faster, I wonder why is that, I mean couldn’t the compiler just analyze what can be const or not even if it is not manually marked as const? Given any random code from someone else I could always manually try to add the “const” keyword to every variable in the code and if there is an error I simply revert it, I just described a general algorithm that automatically marks variables as const, so I wonder why the compiler doesn’t do that internally automatically? I suppose it doesn’t do that because if it did there would be no performance benefits in manually marking variables as const compared to leaving everything not const.
https://redd.it/1bce8qe
@r_cpp
Just curious on the uses of C++
Hi!, I'm a high school student, and I want to learn c++. However, I'm just curious, what uses cases are there for c++ practically. For example, many websites say web development, but just leave it at that. Is c++ really good backend database interactions?, does it have libraries for building full blown windows applications. It would be awesome if people could share!
https://redd.it/1bseixt
@r_cpp
Why is Cpp sin slower than JS?
https://stackoverflow.com/questions/77989813/why-is-sin-slower-in-webassembly-than-in-java-script/78128153
https://redd.it/1bs9ew8
@r_cpp
Backdoor discovered in GitHub xz/liblzma, potential SSH server compromise
https://www.reddit.com/r/linux/comments/1bqt999/backdoor_in_upstream_xzliblzma_leading_to_ssh/
https://redd.it/1bru8wa
@r_cpp
I have a hard time seeing the use for Visual Studio as opposed to Visual Studio Code. Why do you prefer Visual Studio?
Hi!
I've used VS ages ago and since then mostly used Linux and macOS for C++ development but recently I kind of settled on Windows and tried out VS after all those years.
In general, it is fine but I feel like I don't actually gain that much over VSCode? Quite the opposite. I feel like I'm losing some flexibility and even comfort except for a few key elements.
I feel like if you don't do DX12 and need the graphics debugger or have very specific debugger needs that are not available in VSCode, you don't gain anything. And I guess ReShaper and stuff does some fancy refactoring that VSCode can't do but I have never used ReShaper.
I don't want this to turn into a "VS is shit just use VSCode" post. I want to legit know why people like VS proper because maybe I'm missing something. So I won't go into much detail and just say that I feel like VSCode does navigation a lot better, clangd feels snappy af and gives me much better info than VS, the options panels are still as convoluted and annoying to navigate as I remember from VS 2005. The test explorer feels a lot worse than in VSCode (even though it isn't) and the UI is sometimes not as responsive as I'd like.
These are the things that kind of annoy me right now and I feel like VS should be the obvious solution for C++ on Windows and I also feel like this is the general recommendation online but I just don't see it?
Thanks.
https://redd.it/1brhhtn
@r_cpp
Garbage Collection for Systems Programmers
https://bitbashing.io/gc-for-systems-programmers.html
https://redd.it/1bred1z
@r_cpp
Is it possible to #define a newline to be a semicolon and then a space?
That way something like this would compile:
#define \n ;
#include <stdio.h>
//no newline after { since a newline there would generate a syntax error
int main() {std::cout << "Hello World << std::endl
}
https://redd.it/1br7uib
@r_cpp
Why we stopped using macro assemblers?
Here me out, I don't think I've wrongly posted this on r/cpp.
I'm using C++ on daily basis, not the latest standards thought, but still I'm using it really regularly and I'm into MTP, heavy constexpr
usage,... I'm also a big expectant of standardized static reflection, so you could say that I'm basically a giant proponent of doing the most at compile time and passing just what you need to runtime. Now, because we still don't have reflection in the standard, we are quite limited with what is possible to do at compile time(another important component, that eventually needs to land in the standard, is code injection but for the sake of this post lets say that code injection is implied when I say "reflection"), so as probably many of you did before, I also tried to "invent" some kind of compile time reflection. For example, I imagine that many of you have tied the same, I've tried to create a compiler plugin that would pull information from the AST and generate code based on it which is essentially what we will eventually get with the standard proposal but with a nicer API. Parallelly with my attempts to compensate the lack of static reflection facilities, I'm looking at what other people are trying to do at compile time, e.g. a full constexpr
JSON parser has been created by Jason Turner but as far as I know it has limitations primarily because there is no way to pass the dynamically allocated memory to runtime from constexpr
context(another compile time feature that's not available in the language similar to reflection). This is just an example of what people want to do at compile time, and if you ask me, to me it seems that people will find a use case for anything to be done at compile time, or in other words, people want an ability to do whatever they want at compile time. This is something that some languages today allow to a high degree, e.g. zig, circle(c++ compiler). Now here is where I finally start to connect to my title, I am asking myself, if we allow ourself to do whatever at compile time why don't we create a compiler at compile time? I know that this is quite a jump and an extreme, but really, what is stopping us to eventually do that? Even today people are creating full constexpr
enabled virtual machines, what is stopping us to eventually start writing compilers at compiler time?(maybe sanity) And with that thought I somehow landed on a thought "why we stopped using macro assemblers?", maybe I'm wrong but to me it seems that pushing this "do everything at compile time"-train leads to some kind of a "modern macro assembler". We are more and more writing a compile time program that generates a program that will be propagated to runtime and eventually executed. And to be honest, I might not even be against it at all. Maybe, just maybe, there is value in trying to go back and try again with macro assemblers, but with modern macros, i.e. no glorified copy-pasting, maybe try with something closer to a particular oxidized language's macros. I'd be interested in seeing a new spin of an old idea, maybe instead of calling them "macro assemblers" maybe they can be called "compile time assemblers" idk.
I tried to aggregate my train of thoughts here and I hope that it is to some extent understandable what I'm trying to say. I've tried searching for articles of something similar that I'm trying to say here but with no success. Maybe there is already something like a "modern macro assembler" out there that I'm not aware of and I'd be grateful if you would point me at it. In the end I want to say that I'm not really searching for answers here, I'm really just trying to see whether anybody has been thinking about anything similar and whether this is even something that makes any sense to anyone but me. Thank you for reading my wall of text and thank you for any kind of input.
https://redd.it/1bqzvz1
@r_cpp
The White House just warned against using these popular programming languages
The US government sanctioned Office of the National Cyber Director (ONCD), recently released a report detailing that it is recommending for developers to use “memory-safe programming languages.”
This list happens to exclude popular languages, such as C and C++, which have been deemed to have flaws in their memory safety that make them security risks.
\->>full article
What are your thoughts on this?
https://redd.it/1bqnywd
@r_cpp
Why the hate for cpp
Hey I am starting learning c++ (and java for my studies) , why is everyone hating this language ? Is it usefull to learn rust or zig ?
https://redd.it/1bd3w4h
@r_cpp
Is anyone looking at converting a C++ library to with the exception of the standard library to C++20/23 modules?
https://redd.it/1bcxt10
@r_cpp
CppCast: Psychology and Starting Out as a Developer
https://cppcast.com/psychology_and_starting_out_as_a_developer/
https://redd.it/1bcswxi
@r_cpp
C++ safety, in context
https://herbsutter.com/2024/03/11/safety-in-context/
https://redd.it/1bcqj0m
@r_cpp
Any advice for someone like me? I spend around 5-6 hours daily learning.
I’ve started learning cpp its been a little over a month now, but Im struggling to remember a lot of the things that I have learned. Im using “The Complete Reference C++”, “Data Structure and Algorithms by DS Malik”, and a C++ Beginning to Beyond course on Udemy by Frank Mitopoulos. While studying I am able to complete all the given exercises at the end of each chapter or Udemy video tutorial but when I sit to code something from my mind I struggle at it. Especially when I tru to work with Pointers, I have to almost refer back to the book or online references.
https://redd.it/1bcbu30
@r_cpp
StockholmCpp 0x2D, the Intro
https://youtu.be/arpavexXGRc
https://redd.it/1bcakb6
@r_cpp