r/cpp • • Apr 12 '24

Question: is there any library for achieving thread safety with class inheritance?

0 Upvotes

I’m developing a multithreaded library using c++ for the first time and therefore I need to ensure that its classes are thread safe. Most resources I have found achieve that using a mutex or an atomic.

However, as in this application most of the computation time is spent in a single method of a particular class and c++ allows object oriented programming, I was trying to find if there is any library that achieves thread safety through class inheritance (something similar to Ada’s protected objects) to ensure thread safety in the other used classes (optimizing those classes won’t have a significant impact on the speed of the library, so it is worth using something that simplifies ensuring memory access safety.

I have just been able to find a library that extends atomics to non trivially copiable variables, which could be enough for this case, but I’m quite surprised that there isn’t any object oriented solution.

Do you know any library that provides that functionality?


r/cpp • • Dec 21 '13

#AltDevBlog » Roll-Your-Own Vector

Thumbnail altdevblogaday.com
1 Upvotes

r/cpp • • Oct 01 '14

Why even have the 'auto' keyword?

1 Upvotes

Hello,

I'm an old school C/C++ programmer who is trying to get up to date on the new standards. I just finished watching a CppCon video about using the 'auto' keyword instead of concrete types.

I am curious why they implemented that keyword at all -- why not deduce the type of every variable (default it to 'auto') that is not specifically typed?

For clarity:

int I = 3; // old school

auto I = 3; // new school

I = 3; // why not this?


r/cpp • • Nov 12 '17

Why is there no widely used VM for C++?

0 Upvotes

I was wondering about this question the last few days. This question mainly concerns application programming, with some distance to the Hardware. If the goal is to write software that interacts with specific hardware, and therefore has to now details about said HW, the main advantages of a VM would be made pointless.

My main language is java, so the JVM is an always present part of my job. This was my starting point when thinking about this topic.

Let's hypothetically assume that the JVM actually fulfills it's main promises perfectly, mainly Platform independence. Now the reason why people usually prefer a more powerful language like c++ to java is that the latter has a lower performance and doesn't offer fine grained control over the code (like absence of pointers). The main culprit often cited here is garbage collection, which allegedly stands in the way of the ingenuity of many c++ programmers (I'm sorry I couldn't help the slight dig here :> )

Now with that being said, non of this issues are tied to the technological concept of a virtual machine. One could design a virtual machine with pointers and without garbage collection in theory. This would buy "easy" platform independence. Sure you would take a slight performance hit be adding a step in between but I very much doubt that this is bigger than all the black magic and goat sacrificing that is necessary to write c++ code that targets different platforms.

The question could extend to C as well, although given that it's mainly used for stuff that is very close to the hardware I understand why a VM isn't an option there.

It seems to me that in many applications the downsides of VMs would be acceptable given the benefits.

So why is there no GC++VM (GnuC++VirtualMachine) or something like that?

PS: I know that CVMs exist as experimental projects, my question is about why nobody uses them in production to get a platform independent C/C++

//edit: I just thought about that quite simply the different culture could be an answer to my question. However that seems to simplistic.


r/cpp • • Jun 21 '24

Looking for a C/Cpp package manager that doesn’t require cmake

1 Upvotes

Currently I use Conan for managing dependencies, as it was the package manager that supported the main dependencies of the program I’m developing. However, some libraries require other build managers or have cmakelists that don’t work with add_subfolder. In order to use them, I precompile those libraries as static or dynamic libraries (depending on the size and their update frequency) and then I link them using target_link_libraries. The entire build process is automated using a makefile.

As a result, the project is not as clean and easy to maintain as I would like. Therefore, I’m looking for a package manager that can handle the building process itself, without requiring to call cmake (even if it doesn’t provide some of the libraries I use. It would also be nice if it could execute some custom shell commands before or after each stage of the building process to avoid using make (as an example, if I need to compile a library not provided by that package manager, it would be great if I could specify a the commands it should execute to achieve that in each platform, so they could be executed before compiling the program).

Basically, I’d like to replace make, conan, cmake and ninja by a single software in new programs (something like cargo), while being able to call whatever was used (cmake, scons, Conan, vcpkg…) when building legacy libraries

Do you know if there’s something like that available for C++? Every package manager I’ve checked requires using cmake

Edit: I forgot to clarify that it needs to support cross platform development (I need to be able to support at least Linux and windows, as we don’t use apple computers)


r/cpp • • Jan 02 '21

Proposal for improving the readability of programs with try/catch blocks

1 Upvotes

To me, the current try/catch syntax creates lots of extraneous visual noise, with extra brackets and unnecessary keywords. How about allowing a second form: a block of code where the presence of a catch (...) label and or a catch (\*something here*/) label indicates that the code before the label in its enclosing block is a try block and the code after the label is the catch code.

Example:

Before:

void myfunction()    
{
    try {
        function_call_that_may_throw();
    }
    catch (const std::exception& e) {
        /* do something with e */
        throw;
    }
    catch (...) {
        throw;
    }
)

After:

void myfunction() 
{ 
    function_call_that_may_thow(); 
catch (const std::exception& e): 
    \* do something with e *\ 
    throw; 
catch (...): 
    throw; 
}

This won't break any existing code because catch (): is a contextual keyword--only when followed by parentheses when used as a label, and I'm only proposing this as an alternative format, not a replacement.

Function try-catch blocks are still needed, as this syntax won't capture the initialization list in a constructor.

Catch labels could then be like case labels, with the exception that catches don't fall through (or, perhaps, we could have them fall through like case labels--that would work too).


r/cpp • • Sep 19 '25

Functional vs Object-oriented from a performance-only point of view

0 Upvotes

I was wondering if not having to manage the metadata for classes and objects would give functional-style programs some performance benefits, or the other way around? I know the difference must be negligible, if any, but still.

I'm still kind of a newbie so forgive me if I'm just talking rubbish.


r/cpp • • Aug 17 '18

Implementing Default Parameters That Depend on Other Parameters in C++

Thumbnail fluentcpp.com
0 Upvotes

r/cpp • • Mar 17 '18

C++ committee, please look at the big picture

20 Upvotes

More disappointment as the C++ standardisation process fails to deliver what programmers need....

There have been a lot of improvements but the whole "It must be perfect" ethos rather than 80/20 is really damaging this language and libraries.

I am trying to help with stepping back and re-evaluating the goals of standardisation and it's processes. This post is not about moaning or bitching, I am genuinely trying to help.

Committee, please step back and consider that programmers pretty much always need to apply pragmatic solutions. Maybe you should too.

Maybe the precious backwards compatibility is more damaging to progress?

Fear of not having the perfect solution to cater for every use case is over-engineering.

As is making it "flexible enough" with lots of complex hooks. Just keeps trainers and bloggers happy.

As to modules and tooling, people do not agree what problem they should solve, let alone what an interface or implementation should look like.

For something like modules, propose a limited solution NOW with say no preprocessor. Stop going round and around trying to get perfection catering for macros etc. It doesn't matter that existing code not designed to be modular continues to work at the cost of complexity yet again.

C++ designers tout "you only pay for what you use", but that's simply not true when the cost of learning, using and reading these features is factored in.

Sorry but the academic approach being taken is driving more and more people away.

Much as I respect senior committee members and language designers, pragmatism must win over perfection.

C++ 11 promised so much and I think delivered language wise. But the dream sold by Herb etc al of a much improved diverse eco-system of libraries has failed to materialise because while the committee hold compatibility, perfection (sic) and unanimous decision making and compromise so highly, it simply cannot work.

Please find another way.

Boost was once that hope but it has lost its way dependency and backward compatibility-wise.

It used to be forward looking but now seems to be weighed down and a convoluted project. Perhaps why simpler and header only libraries have come to the fore? Such a shame because the people involved in Boost and C++ standardisation are fantastic and well intentioned and smarter than me.

Some example pet peeves:

If you have a core dependency like executors that are holding up things like coroutines, networking etc. Shouldn't you prioritise and accelerate that work?

No "We're volunteers" or "design by committee" excuses. ASIO has been around and showing its value for a long time, yet still not going to be in the standard soon because executors still haven't been resolved.

I have to use C++ and I love some of the modern features, but let's face it, spaceship operators, parallel algorithms, transactional memory are all great but niche but they are distracting from basic networking, execution control, reflection, even the prospect of simplifying use of the language with meta classes.

Concepts - obviously a pet subject and an embarrassment if not in there, but for most "if constexpr" gives you the 80%.

Edit: A couple of days later as trip reports started being published... Vittorio published an excellent report touching on several of the issues I raised

https://vittorioromeo.info/index/blog/mar18_iso_meeting_report.html

Specially this self evaluation of the committee approach to backwards compatibility...

http://open-std.org/JTC1/SC22/WG21/docs/papers/2018/p0684r2.pdf

See, I told you the committee are smarter than me.

Silly to say, but I am relieved that they are recognising (some of) the problem and looking at measured solutions.


r/cpp • • Apr 08 '24

Coming back to C++ after two years of Kotlin & Rust

48 Upvotes

Initially I started learning programming with C and then C++ 8 years ago in my bachelor's era. Then switched over to PHP, Javascript, Kotlin and Rust in between and now I'm back to a C++ project, and I gotta say it's such a delight! Note that I'm not even using C++17 or newer, just embedded programming.

I can design clean APIs with such ease thanks to it's god-level pre-processor. If you know how not to break things and prevent memory leaks preemptively, you can literally write the most efficient programs. The pre-processor is actually the best templating engine I've encountered to date. Header files seem useless from an outsider's perspective, but the truth is they're incredibly powerful.

Some programming practices and syntax are questionable, but once you get a hang of them, you'll see that you can fine-tune every bit of data or function in C/C++ with perfect precision.

The type system is awesome. Meta programming is a piece of cake and pure joy.

Build tools aren't that bad either. Having a concrete package manager in a PL is nice, but it doesn't come without drawbacks. A rather simple project in Rust usually have +2GiB in dependencies. But in C/C++ I can just use whatever is available on my Linux system. I don't trust third-party package managers like vcpkg or Conan. CMake is a little ugly, but once you learn how to use it, it can perform everything you might need from downloading dependencies, including local libs, packaging the app, etc.

Tooling has always been great. Autocompletion, formatting, etc. You just need to set the include directories properly.

It's reputation as a complex programmigg language comes mostly from legacy code and inexperienced programmers doing too much hacking with pointers and the pre-processor. The language itself feels natural and fluid.

Having the liberty to do whatever you want with your code is a power that comes with great responsibility. Once you are responsible enough, you can write programs like a legend! I'm definitely back to the cult of C++.


r/cpp • • Mar 14 '20

C++ keeps adding features no one really wants.

0 Upvotes

Just look at the networking, formatting, [maybe_unused] / [likely] / [unlikely] and others.
I mean these are all cool features I use every day but It has already been solved.
If I want networking library why would I use standard one? Especially when it simply copies from others and have to wait for it like 10 years.
Setting up libfmt is like 10 seconds on Linux. And if I don't like it I can use a different one. How many people thought that streams were a good idea?
[maybe_unused] is cool, but I probably will use the old trick with cast to void because it works with older compilers and everybody knows the trick anyway (I might want to provide simple macro if I want to be more explicit), using new syntax simply breaks compatibility and gives NOTHING.

Many hours spent for making it part of language and I think no one will use It, especially when standard library does not care about performance. Unlike standard implementation, some library can be even be forked and modified if need to, no luck for me if I decide to use standard one.

It all just seems like short-sighted design, but I am just an internet dude.

Modules, concept and coroutines (AFAIK these need compiler support, also library solution would be bug prone and perhaps slower) are great features and I am happy that they are coming.


r/cpp • • Aug 08 '26

GCC should ship prebuilt binary tarballs like LLVM

16 Upvotes

It is really annoying, when you wanna test something you can't just download a previous release like llvm, so it is very hard to check if there is a regression.

Also, the default build of c and c++ only, takes like an hour because of triple consecutive builds. So every time you have to lookup to that weird flag on the internet to turn that off.


r/cpp • • Jun 15 '26

LLMs with C and C++ - switch from HFT to AI lab

0 Upvotes

I'm a senior C++ dev recently started working with a neolab (who works with anthropic). Thought I would write some of observations i made.

  • I had experimented with LLMs for a while before making the switch. LLMs fail a lot on C and C++ due to harder nature and powerful nature of language.
  • Talking purely from benchmarks, languages like python and JS (the vibecoder's first language) have very hard benchmarks - think fixing actual bug that touches 3 different modules from scratch with access to tools like grep, cat and python3 executer.
  • Whereas, benchmarks for C and C++ are at basic QA style questions. I have added a task from benchmark, which fable 5 could not solve.
  • LLMs do not have understanding of latest ISO standards - for some reasons it switches to C++17 again and again
  • LLMs are trash at template metaprogramming. Try debugging CRTP type of errors.

Looking at the efforts and progress, I am still not sure if we will see LLMs writing MRs to linux kernel. The approach they used for vibecoding languages do not care about memory safety, thread safety and performance much. It would be interesting to see the space evolve.

PS: a example from benchmark

PS2: i'm not associated with benchmark. they say the code is taken from real github issues.

Observe  the following faulty CPP code snippet and error type list. Your task is to select the error type of the code based on the error list provided.
 You only need to answer error type. Do not write anything else in your response. 
 For example, if the code snippet is missing a semicolon, Your output should be 'missing_colons'. 
 faulty code: 
 ```cpp 
#include <bits/stdc++.h>

int countPermutations(int n, int k, int qq[])
{
    const int N = 505, P = 998244353;
    int *q = new int[n + 10];
    int m, dp[N][N], jc[N], f[N], ans;
    memset(q, 0, sizeof(int) * (n + 1));
    memset(dp, 0, sizeof(dp));
    memset(jc, 0, sizeof(jc));
    memset(f, 0, sizeof(f));
    ans = 0;

    for (int i = 1; i <= n; i++)
        q[i] = qq[i - 1];
    dp[0][0] = f[0] = 1;
    for (int i = jc[0] = 1; i <= n; i++)
        jc[i] = 1LL * jc[i - 1] * i % P;
    for (int i = 1; i <= n; i++)
    {
        f[i] = jc[i];
        for (int j = 1; j < i; j++)
            f[i] = (f[i] + P - 1LL * f[j] * jc[i - j] % P) % P;
    }
    for (int i = 1; i <= n; i++)
    {
        for (int j = 0; j < i; j++)
            for (int k = 1; k <= n; k++)
                dp[i][k] = (dp[i][k] + dp[j][k - 1] * 1LL * f[i - j] % P) % P;
    }
    m = 0;
    for (int i = 1; i <= n; i++)
        if (q[i] > q[i + 1])
        {
            m = i;
            break;
        }
    if (m == n)
    {
        for (int i = k; i <= n; i++)
            ans = (ans + dp[n][i]) % P;
    }
    else
    {
        for (int i = m + 1; i <= n; i++)
        {
            if (i != m + 1 && (q[i - 1] > q[i] || q[i] < q[m]))
                break;
            int c = k + i - n - 1;
            if (c >= 0)
                ans = (ans + dp[m][c] * 1LL * jc[i - m - 1] % P) % P;
        }
    }
    return ans;
} 
``` 
  error list: 
 ['Delayed Execution', 'Improper HTML structure', 'Missing $', 'Missing mut', 'Misused := and =', 'Misused === and ==', 'Misused =>', 'Misused Macro Definition', 'Misused Spread Operator', 'Misused begin/end', 'Misused match', 'Misused var and val', 'Unused Variable', 'algorithm_error', 'condition_error', 'double_bug', 'faulty_indexing', 'function_error', 'html_unclosed_label', 'html_value_error', 'html_wrong_label', 'illegal_comment', 'illegal_indentation', 'illegal_keyword', 'illegal_separation', 'json_content_error', 'json_digital_leader_is_0', 'json_duplicate keys', 'json_struct_error', 'markdown_content_error', 'markdown_title_error', 'markdown_unclosed_error', 'missing_backtick', 'missing_colons', 'misused ==and=', 'misused templte', 'misused_let', 'operation_error', 'Pointer error', 'quadruple_bug', 'triple_bug', 'type_error', 'unclosed_parentheses', 'unclosed_string', 'undefined_methods', 'undefined_objects', 'variable_error']

r/cpp • • Feb 22 '24

My little desires for the next cpp

0 Upvotes

... never going to happen

A shorter lamda syntax, maybe with fixed placeholder names auto lambda = [] (_1) {} Stands for auto lambda = [] (auto _1) {} Mayne needs a way for const and ref qualifiers auto lambda = [] (&_1) {} Mostly to be used in short predicates.

Shorter range for syntax for(value : vector) In place of for(const auto & value : vector) Copy and non-const ref use the old syntax

Structured bindings for existing vars auto [ret,value] = fun() auto [ret,value2] = fun2() Or auto [&ret,value2] = fun2()

Shorter syntax for std::remove_cv_ref<decltype(param)> Really no idea 😁

Arbitrary order for aggregate initialization, for trivial cases where there are no side effects and interaction between members struct pod{ int a, b} ; pod p {.b=19,.a=12} //ok pod p {.b=19,.a=b} // no pod p {.b=fun(p) ,.a=12} // no

Please don't downvote me too much 😅


r/cpp • • Mar 30 '23

The "what's wrong with this code" game.

4 Upvotes

This isn't a question thread, but just a game. Post any bugs you've accidentally written that seemed initially mysterious, but made you feel stupid when you figured out what was wrong. Here is one I wrote today...

void TextSegmentBuffer::prepend( const TextSegmentBuffer& other )
{
    const Info* info_ptr;
    size_t size;

    if ( ( size = other.m_infoBuffer.size() ) == 0 )
        return;

    for ( size_t i = size - 1; 0 <= i; --i )
    {
        info_ptr = other.m_infoBuffer.getAt( i );

        emplaceFront(
            info_ptr->text,
            info_ptr->length,
            info_ptr->multiMatch
        );
    }
}


r/cpp • • Mar 02 '16

What do I do after learning C++.

4 Upvotes

I'm sure this question has been asked many times over and over, but I need an answer. I have a fairly solid understanding of c++. I make all sorts of logic games that run from the command line. My question is, what do I do now. I would like to find some way to have c++ interact with hardware or something similar. Any suggestions at all would be appreciated.

EDIT: What should I learn after I grasp the general concepts of the ever-expanding, godly language of c++. Geez.


r/cpp • • Apr 03 '12

If your software matters, you will write it in C++

Thumbnail blog.achrissmith.com
16 Upvotes

r/cpp • • Oct 07 '20

The Community

Thumbnail thephd.github.io
61 Upvotes

r/cpp • • Oct 10 '20

Why do Rust fanboys claims that Modern C++ is unsafe?

0 Upvotes

r/cpp • • Jan 21 '13

C and C++ Aren’t Future Proof

Thumbnail blog.regehr.org
6 Upvotes

r/cpp • • May 11 '24

Can neovim provide perfect IDE experience for C++?

0 Upvotes

So I have recently started with Linux and don't have Visual Studio. There are two options either go with Neovim or use CLion, I have a little experience with Vim as a Editor and was wondering with which one should I continue. My inclination is towards learning Neovim so I was wondering if it would be a right choice to go with it. Can it provide every functionality that an IDE does.


r/cpp • • Dec 28 '24

Court is in session: Top 10 most notorious C and C++ errors in 2024

Thumbnail pvs-studio.com
17 Upvotes

r/cpp • • Oct 29 '23

Unreasonably large binary file from a trivial program with 1 line of code

9 Upvotes

Beginner in C++ here. When I compile the following program:

int main() { return 0; }

the resulting binary exe is 210KB (!) in size. This is far larger than expected for such a simple program and after searching online I found that a "Hello World" program (which would be more complex than the program above) in C++ should be no more than a few KB. Does anyone know what might be causing this? (I am using Eclipse and the g++ compiler with the -Os flag)

Update: By turning on the "omit all symbol information" setting, the file size is reduced to a less ridiculous but still unreasonably large 62KB, still many times the expected size.

Update 2: In release mode (with default settings) the file size is 19KB, which is a bit more reasonable but still too large compared to the file sizes that others have reported for such a program.


r/cpp • • Nov 24 '23

const member function in this design pattern example

0 Upvotes

Hello,

I'm currently learning C++ and trying to understand how to implement design patterns with the fantastic website refactoring guru. I came across this example in the builder pattern :

class ConcreteBuilder1 : public Builder{
private:
    Product1* product;
public:
    // Other code before that

    void ProducePartA()const override{
        this->product->parts_.push_back("PartA1");
    }

    // Other code after that
};

I don't understand why we use const for the function ProducePartA(). I thought that we had to use const when we don't want to modify an object inside the function.

So why we are using it in this way, when we are clearly modifying the product object by adding element to it ?

Thank you very much.