r_cpp | Unsorted

Telegram-канал r_cpp - C++ - Reddit

-

Stay up-to-date with everything C++! Content directly fetched from the subreddit just for you. Join our group for discussions : @programminginc Powered by : @r_channels

Subscribe to a channel

C++ - Reddit

About this inline

I've heard inline should be used while defining short functions but over use of inline may slow down the program. So say there are some functions like five or six which only returns values or say like five or six short one line functions. Is declaring them inline efficient or not a good practice? I'm confused in inline usage.

https://redd.it/1hr0abf
@r_cpp

Читать полностью…

C++ - Reddit

is Visual Studio code for macOS an IDE

I want to learn C++ for software development but Visual Studio is not on Mac anymore so does Visual studio count as an IDE

https://redd.it/1hqmqre
@r_cpp

Читать полностью…

C++ - Reddit

My Favorite Talk of 2024: Message Handling with Boolean Implication — Feel Free to Share Yours

And the Oscar goes to...

Ben Deane for his portrayal of George Boole in

https://www.youtube.com/watch?v=aIPvb\_PaI1A

It is hard to explain why this talk is so amazing without recapping it, and I think Ben is much better storyteller than I am. I will just say that it all fits together so elegantly and shows off modeling power of C++.

I prefer this 28 minute version compared to longer versions since for me pacing is much better than in longer talks, but if you prefer slower presentation there are longer versions of this talk.








https://redd.it/1hqhr88
@r_cpp

Читать полностью…

C++ - Reddit

Unexpected behavior of static_assert on concept

Recently I've experimented a bit with variants, concepts and static_asserts. My finding boils down to the question why the following snipped compiles on all three major compilers.


#include <variant>

struct A {};
struct B {};

struct VisitorAB
{
void operator()(A) const {};
//void operator()(B) const {};
};

template <typename VisitorT, typename VariantT>
concept Visitor = requires(VisitorT&& visitor, VariantT&& variant)
{
std::visit(visitor, variant);
};

void test()
{
std::variant<A, B> var;
VisitorAB vis;
//does not compile because overload for B is missing
//std::visit(vis, var);

//does compile despite missing overload
static_assert(Visitor<VisitorAB, std::variant<A, B>>);
}

https://godbolt.org/z/YodTc9Yhv

&nbsp;

The `static_assert` at the end of `test()` passes despite the fact that the call to `std::visit` does not compile.

I expected it to fail because this seems to be basically the same as the `Addable` examples provided on cppreference ([Requires expression](https://en.cppreference.com/w/cpp/language/requires#Requirements)).
The comment there states "the expression “a + b” is a valid expression that will compile", since `std::visit(visitor, variant);` does not compile, I expected my `Visitor` concept to not be satisfied for `VisitorAB` (with one overload missing) and `std::variant<A,B>`.

&nbsp;

All three major compilers agree on this so I'm almost certain that I'm missing something but the following observation resulted in my suspicion that a compiler bug might be involved:

struct VisitorAB
{
//void operator()(A) const {};
void operator()(B) const {};
};

Changing the snippet like this will make the `static_assert` fail with all three compilers.

&nbsp;

After testing some other permutations, the `static_assert` seems to fail when the visitor struct has no call operator for the first variant alternative but passes as soon as the first alternative is covered.

&nbsp;

If this behavior is expected, can someone shed some light on why?

Wasn't sure if this is appropriate for r/cpp, if not I'll remove it and post it on r/cpp_questions instead.

https://redd.it/1hqgfk8
@r_cpp

Читать полностью…

C++ - Reddit

Frustration status of finite state machine libraries in cpp

This seems like a trivial problem: implementing a finite state machine to get more maintainable code, easier to debug and refactor some legacy code.
And yet I am completely stuck at step 0 which is finding a suitable library or decide to go for a custom implementation of a fsm.
My research basically gives me 3 options that are bad:
- Reinvent the wheel and implement a custom finite state machine library that suits requirements and probably lose a lot of time and energy on maintenance of said library.
- Use boost msm or statechart but they are bloated and use old style C++, steep learning curve for new comers and pretty awful interface imo
- Use some modern open source implementation of fsm from an unknown source with absolutely no guarantee it is still maintained let alone 5 years from now.

The messiah seemed to be boost sml bust guess what it is not part of boost and does not seem to be very active since the initial hype it got…
There is ton of small implementations here and there but none that get a large community support I find it frustrating.
Guess I’ll just stick to enums and switch cases then. Except if anybody has a better view on the subject ?

https://redd.it/1hqdb2j
@r_cpp

Читать полностью…

C++ - Reddit

C++ Coding skill assessment online resources

What resources do you use for preparing C++ interviews ? I know hackerearth and codesignal ? Are there any other good resources you know ?

https://redd.it/1hqci2s
@r_cpp

Читать полностью…

C++ - Reddit

Question

I'm learning c++ so I could be in the area of games, and the only thing I'm using rn is an app called programming hub, I just know a small bit on c++ and it seems very complex but understandable and the same tkme. I wanna say this app is teaching just a small amount of what c++ is.

So I was just wondering if there is anything that is pretty cheap/free for me to expand my knowledge on this, and if you guys have any advice, that'd be great.

(The way people talk about c++...it can't be that difficult right?)

https://redd.it/1hq8xek
@r_cpp

Читать полностью…

C++ - Reddit

Confusing std::array CTAD compiler error

Check out the following godbolt link and read compiler error before reading further.



What did you conclude from above?

Maybe that std::array CTAD is only available in C++23?



Well welcome to C++. Compiler message is mostly useless, CTAD works fine even in C++17 if you include <array> header. As for why it works in C++23: without investigating I would presume some internal reorganization of headers drags in necessary functionality.


There are also other insane error you can get when this happens, e.g. too many initializers


To be clear: I know implementations do not do this because they are evil, they try to reduce compilation speeds and sometimes we end up with programs that confuse compiler... but that does not change the fact this can be quite confusing to beginners.


P.S. I know I will get a ton of comments that only n00bs could make mistake of not including correct header, that if you read the error it is clear it is from pair header, it is clear array is fwd declared, etc. ... but I am certain this can happen in real projects easily, especially for junior developers... You start writing some code, include few headers, try CTAD, see it does not work since compiler tells you deduction guide does not work, you assume it is not supported, then you hit the too many initializers error, you google it, SO answer tells you you put too many numbers inside {}, you are confused because you put correct number of values inside {}...





https://redd.it/1hpq00l
@r_cpp

Читать полностью…

C++ - Reddit

Skipping boring functions in debuggers
https://maskray.me/blog/2024-12-30-skipping-boring-functions-in-debuggers

https://redd.it/1hpwwk7
@r_cpp

Читать полностью…

C++ - Reddit

GUI in c++

I have been learning c for a year now and shifted to cpp a month ago.I have learned enough in cpp to start building projects. I had to build a project in c last month where I had decided to make a Sudoku game with interactive interface using Gtk in c. Gtk was difficult to learn due to various reasons. So I had to drop the GUI part and made it in console itself, but now I want to learn gui programming in cpp and I have seen many people suggesting Qt but there are not many resources available(for free). Is there any other language(less written) easy for beginners, and has resources available and also would help me in future.

https://redd.it/1hnks3c
@r_cpp

Читать полностью…

C++ - Reddit

Is CPP "safe" from AI coding bots in the future?

The title kind of says it all but essentially I've started feeling really concerned with the quality and speed at which AI outputs code nowadays. For a lot of advanced coding tasks it is still a ways off, but it does very well in mainstream, well-contained problems like web work and the likes.

I've honed a lot of skills in Python (to eat) and C# (Unity - hobby) and I'm beginning to think that in a couple of years it might be extremely hard to find actual well payed jobs as a Python programmer unless you are an absolute expert, because most of it will probably be done by AI.

I've turned to C++ in hopes of learning how to optimize code to perfection and work on harder / more complex (lower level) problems. My question to you experts / gurus is: is C++ dev a "safe" bet on the future in terms of programming jobs? Are any of you feeling concerned about this AI rush or do you feel like there will always be a need for talented C++ programmers?

What are your thoughts in general about the state of the market for programming jobs and how it will evolve over the next 20 years with AI?

https://redd.it/1hnh0ux
@r_cpp

Читать полностью…

C++ - Reddit

Is it normal to feel lost?

Okay gurus here and cpp experts I’m seeking your advice not some bashing. I’m 40 and had to fiddle with Linux in my older days to actually have a working computer. For 2 months I started to learn cpp, I just had a realisation about code and got fascinated with the process. I enrolled in courses and I’m cruising nicely. Understanding concepts and giving them time to absorb them then move on. At a very slow pace I reached functions now after string manipulation.

I do isolate concepts like loops and make some small exercises to prompt the user and chose between A and B options for example then proceed with the choices and handle any invalid inputs with a while loop. Sometimes it is a do while and it will do the job as well.

Sometimes I would make a 2d vector and have some exercises with them as well with for loops. I did the numbers pyramid, the story and the tic tac toe as well on my own with very minimal help.

Just after this little context, I also come from an electrical engineering background which saved me with booleans.

Now the question is;
Why is it that some days I feel like a huge dumb bucket of nothingness. Other days I feel like I understand what I am doing.

Is this normal and okay in your experience? Or is it that I’m doing something wrong and feeling totally lost.

Sorry if this feels like venting more than a question. Any recommendations ? Advice?

Thank you guys.

https://redd.it/1hnbbqy
@r_cpp

Читать полностью…

C++ - Reddit

What version should I be using?

New programmer. coming from power platform and C#. What version of C++ should I be coding in? C++ 11? Thanks for your consideration!

https://redd.it/1hn4c8j
@r_cpp

Читать полностью…

C++ - Reddit

What is null?

say you get asked this at an extremely c++ heavy, competitive company. how do you answer this? and how do you answer the follow up - how big is null?

https://redd.it/1hmp5z5
@r_cpp

Читать полностью…

C++ - Reddit

Reflecting on Custom Attributes in C++26?

Will it be possible to reflect on custom attributes in C++26? or future standards?
How?
For instance, (and by no means, I'm limiting the use case to this particular example), it would be great to have something like this:

struct CliArguments {

[[cli::flag("--help", "-h", "show help information")]]

bool help = false;

[[cli::option("--key-file", "-k", "paht to key file")]]

std::string keyFile;

[[cli::option("--jobs", "-j", "number of concurrent jobs", 4)]]

int jobs = 4;

};


and inspect cli:option for class CliArguments.

https://redd.it/1hmm55o
@r_cpp

Читать полностью…

C++ - Reddit

Json Deserialization Woes

I've written code to deserialize json in go and cpp. I'm trying to understand why date parsing in my cpp code is slower than my go code.

For below, I'm measuring performance in terms of time taken to parse a single message. Messages are <10KB, so I'm artificially making them larger and reading them as slices because I expect to receive a variable length array of messages in prod. I'm not using any optimizations because I want to be able to compare the languages from default settings. I've tested my code using abseil and Howard Hinnant's date packages. I'm using glaze json for json parsing.

For 12/15 test scenarios, C++ is 10x faster atleast. 1 of those test cases, cpp's p99 was close to the p50 for golang, which isn't terrible. 2 of the test cases the cpp p50 was higher than the go p99.

The 2 test cases try to parse a single RFC3339 datetime string for each message. Just out of curiousity, I read those fields are strings and performance jumped 10x.

Is there an obvious reason, other than skill level, why date parsing in cpp is so much slower? Is it related to the underlying parsing lib implementation or something else?

godbolt

https://redd.it/1hqogni
@r_cpp

Читать полностью…

C++ - Reddit

Feeing hard to understand Coroutine in C++20 and beyond

Hi everyone, execuse me for my bad English, I am not native speaker.

Recently, I read and try to use Coroutine (Coro for short) and find out it quite hard to construct it, especially the promisetype. I see it is really powerful since using promisetype enables users to fully control the lifecycle of a Coro, which is excellent if compare to Coro in another languages.

However, it is hard to understand how to actually implement the await* method, such as awaitsuspend. I tried to put a few log message to see when the Coro suspend and resume, but end up more frustrated.

Some search results claimed the design of Coro is clunky. I am not sure if it is true for experienced developers?

How do you think about the Coro? Where can I find more friendly resources to undersand and use it properly? Thank a lot.

https://redd.it/1hqj6ve
@r_cpp

Читать полностью…

C++ - Reddit

Returning optional references

In my experience as a C++ developer, I've encountered several methods for returning optional references. I'm looking for opinions on what I've encountered and other possible options. I don't think there's a "best" solution, my goal is to gather pros and cons for the options available.

This is a generic question, not for a specific problem/application. But to give some context I give the following example:

class SomeClass {
public:
void DoSomethingThatSetsValue();
const SomeOtherClass& getValue() const;

private:
std::unique_ptr<SomeOtherClass> value {nullptr};
};


The problem with this class is that when calling the getValue() function the value might not be set. One might say to use a std::optional, but that copies the value of the member variable. This discussion is targeted at situations where you can't create a copy.

As mentioned I've seen multiple options to solve this problem. Here are some:

***Using the standard library with: std::optional with reference wrapper***

//Getter
const std::optional<std::reference_wrapper<SomeOtherClass>> getValue() const {
if(value){
return std::optional<std::reference_wrapper<SomeOtherClass>>(*value);
}
return std::nullopt;
}


//Where it's called
auto x = theInstance.getValue();
if (x.has_value()){
auto actual_x = x.value().get();
// Do something with actual_x
}

**Pros:**

* Built-in solution in C++ and standard library
* No raw pointer access

**Cons:**

* to get the actual value a train of `.value().get()` is required
* Nested containers

***Return a raw pointer***

//Get member
SomeOtherClass* getValue();

//Where it's called
auto x = theInstance.getValue();

if (x!=nullptr){
// Do stuff with x
}


**Pros:**

* Built-in solution in C++
* It's common practice to check pointers for null value before use

**Cons:**

* It's a raw pointer
* Less safe (because it's a raw pointer)
* Checking for null value is not enforced

***Create a*** `hasValue()` ***function***

//Get member
bool hasValue(){
return referenced_value != nullptr;
}

//Where it's called
if (theInstance.hasValue()){
auto x = theInstance.getValue();
// Do stuff with x
}


**Pros:**

* No raw pointers
* Clean coding

**Cons:**

* Not enforced to call hasValue
* Must implement has function for each optional reference

***Smart Wrapper***

template <typename T>

class SmartOptionalWrapper { //Better name pending :)

public:
SmartOptionalWrapper() = default;
SmartOptionalWrapper(T& value): referenced_value(&value) {}

//Inclomplete class misses assignment operator for value, copy/move constructors, etc


bool hasValue() const {
return referenced_value != nullptr;
}


T& getValue() {
return *referenced_value;
}

private:
T* referenced_value {nullptr};
};



//In class:
SmartOptionalWrapper<SomeOtherClass> getValue(){ return value; }

//Where it's called:
auto x = theInstance.getValue();
if (x.hasValue()){
// Do stuff with x
}


**Pros:**

* No raw pointers
* Clean coding
* Only have to write this class once and use everywhere

**Cons:**

* Not enforced to call hasValue

***Boost optional***

I have no experience with boost, but the boost::optional appears to have the option to store a reference (this differs from the std::optional).

Even though I have no experience with this variant, I can think of some pros and cons

**Pros:**

* No raw pointers
* Clean coding
* Present in an already available library

**Cons:**

* Relies on boost, which is not available (or wanted) in all code bases.

***Your options / opinions / pro&cons***

I'm curious about your options/opinions to solve this problem.

https://redd.it/1hqhth8
@r_cpp

Читать полностью…

C++ - Reddit

Are there any easier methods to remember cpp library function calls!

Hello everyone , hope you all have a great day! Recently I start to forget most functions from libraries like zlib , hashing libraries and other windows apis . I am not good with remembering things and recently oploids that I got from a surgery ,make it worst ! So what are your thoughts about making it easier ?

https://redd.it/1hqedru
@r_cpp

Читать полностью…

C++ - Reddit

Collective Amnesia? - Peter Sommerlad - Keynote Meeting C++ 2024
https://www.youtube.com/watch?v=g6QYGW-TwwY

https://redd.it/1hqc9jz
@r_cpp

Читать полностью…

C++ - Reddit

Project idea related to cryptography

I want to make a tool/software related to cryptography that will be useful to other people,
I do have some knowledge in cryptography but never really tried to implement it in programming
Any recommendations for some Intermediate level projects?

https://redd.it/1hqad1n
@r_cpp

Читать полностью…

C++ - Reddit

Templates/Concepts

Are there any good books that go more in depth about templates, concepts, and similar topics?

https://redd.it/1hq7we8
@r_cpp

Читать полностью…

C++ - Reddit

Starting my C++ journey. Any Tips? Also just kind of my Opinions on things, happy to hear yours.

Why C++?:

Hi, I come from Game Development using Unity but kind off started to loose the fun out of it and wanted to try something new. Also the job market in Game Development is really bad and Indie Development is really competitive. So I was just looking around for several months and tried out new things like Rust, Godot and Web Dev. But none seemed to really interest me. Also there are too many people in Web Development for me because getting into it is pretty easy. I wanted something more difficult, more complex but still fun. So I decided on C++ and graphics programming (you know, Opengl and so on).


What I already know:

I already know some (really just a bit) c++ and opengl/sfml. I never learned c++ specifically but rather picked it up while following tutorials. I followed LearnOpengl.com until textures (so I did textures but not the 3d stuff) and followed like 1 or 2 sfml tutorials. So I already know programming from programming before + c# but I don't really know anything about c++ or graphics libraries.

What my Goal is:

My Goal is to be able to make simulations (fluid, particle, ...), games, visualize stuff, render things and more. I also would like to get a job in Game Engine programming or simulation programming or visualizing things (just graphics programming) and do projects on the side. (btw. if you are a graphics programming or somewhere in that area, how do you like it? Any tips on how to get a job in it?)

My Plan:

I know that this will be hard and that you can't really finish learning C++ and graphics programming and that I will need to know Math and everything. I know that it is hard.

But my plan is to upload 1 video per week to YouTube and write 1 blog per week (basically the same content) where I share my progress.

I will go through LearnCpp.com and maybe TheChernos series and maybe other things (what would you recommend? Should I do LearnCpp.com until the end?).

(Randomly talking about TheCherno):

I watched TheCherno before relatively often. Not his tutorials but his code reviews. But I always feel like TheCherno is criticising and roasting too much. I know that people send their project to get roasted and get good feedback and sometimes they even explicitly say that he can roast them as much as he wants but still. This could also be because I don't really know c++. I feel like most things that he says are wrong are just his personal opinion on how he would do it even on smaller things that don't make a huge difference. But like I said, I don't really know c++ so pls tell me your opinion on TheCherno. Maybe when I understand c++ I will agree with him and would also criticise so much.

(Back to my plan):

Then (should I finish LearnCpp.com and other resources before I start this or should I do both things parallel?) I will probably get into some 2d stuff first (SFML probably but you can say your opinion), like water simulations and particle simulations. Maybe making a simple sprite drawing app and making a game. Then get into OpenGL with LearnOpenGl.com and maybe another resource (which one would you recommend?). With that knowledge I will pretty much just do cool projects with c++ and OpenGl and learn while doing them. Later on I will probably learn Vulkan and/or DirectX so I can actually get a job.


So, what do you think? Pls give your opinion about everything and correct me if anything is wrong. But be respectful. Do you think showing my progress on a YouTube channel and blogging it could be fun to watch/read? How in detail would you like me to go in the videos/blogs? Anything huge where you agree on? Maybe that I shouldn't even learn c++ or something xD?




https://redd.it/1hq0x74
@r_cpp

Читать полностью…

C++ - Reddit

Has anyone figured out yet how to get clang-format to not bizarrely try to align chained methods
https://i.imgur.com/L6r1NnH.png

https://redd.it/1hnps39
@r_cpp

Читать полностью…

C++ - Reddit

C++ Design Patterns - The Most Common Misconceptions (2 of N) - Klaus Iglberger - CppCon 2024
https://www.youtube.com/watch?v=pmdwAf6hCWg

https://redd.it/1hniyw1
@r_cpp

Читать полностью…

C++ - Reddit

C++ flowcharts

Hi everyone, I'm a computer science student and I'm having some problems with the flowchart representation of some c++ programs. I kindly ask if someone can help me to graph the flowcharts of the c++ codes that I provide. I thank everyone again for the collaboration and please let me know if anyone is available.

https://redd.it/1hnff8u
@r_cpp

Читать полностью…

C++ - Reddit

trying to start with C++ Windows 11

hi im on windows 11 and i want to start with C++ and Visual Studio what do i need to install?

https://redd.it/1hn9vfs
@r_cpp

Читать полностью…

C++ - Reddit

Looking for advicec about, how to find yourself?

So hello, I'm writing to vent a little and ask for advice. I've been studying C++ for a year, studying the basic syntax, the compilation process, how the compilers themselves work, QT Framework, stl, pqxx, and some other minor libraries. But I still can't figure out what exactly I want, as if I don't want something difficult, but as if there's some charm in it. I'm interested in gui programs, but so far QT has been difficult, maybe there will be some advice? I would like to hear how to find myself in this field?

https://redd.it/1hn23pb
@r_cpp

Читать полностью…

C++ - Reddit

strict_weak_order constraint not satisfied by custom operator<=>?

See the code below, where I've defined a custom operator<=>. The 2nd call to set\_difference doesn't compile because gcc claims the 'strict\_weak\_order' constraint is not satisfied. If I set the operator<=> = default, it works. Is this the expected behavior? How can I make it work with my custom operator<=>?

#include <algorithm>
#include <set>

struct X {
  std::strong_ordering operator<=>(const X&) const noexcept;
};

void f() {
  std::set<X> v1, v2, diff;
  // compiles fine:
  std::ranges::set_difference(v1, v2, std::inserter(diff, diff.begin()), std::less{});

  // doesn't compile:
  std::ranges::set_difference(v1, v2, std::inserter(diff, diff.begin()));
}

[https://gcc.godbolt.org/z/bTG4WfPb8](https://gcc.godbolt.org/z/bTG4WfPb8)

https://redd.it/1hml9af
@r_cpp

Читать полностью…

C++ - Reddit

Suspected MSVC x86 64-bit integer arithmetic miscompilation bug

#include <cstdio>
#include <cstdlib>

int main() {
struct {
long long a = 0;
long long b = 1;
} x2;
int i = std::rand() & 1;
std::printf("%lld\n", -xi.a);
}

Compiled by MSVC for x86, with enabled optimization /O2 or /O1, this code prints -281474976710656.

https://godbolt.org/z/5sj1vazPx

Someone pointed out that the read for the second 32-bit part of a 64-bit integer got an incorrect address.

call rand
and eax, 1
add eax, eax
mov ecx, DWORD PTR
x$esp+eax*8+32
neg ecx
mov eax, DWORD PTR x$[esp+eax+36] ; !
adc eax, 0
neg eax
push eax
push ecx
push OFFSET `string'
call
printf

It's reproducible on all versions of MSVC available on Compiler Explorer.

Is it a known issue? Because if it isn't, I'd be curious how this didn't happen until today while it doesn't look like extremely hard to happen.


https://redd.it/1hmlb8l
@r_cpp

Читать полностью…
Subscribe to a channel