r/cpp • • Jul 05 '26

C++26 ends a 40-year footgun

86 Upvotes

Reading an uninitialized variable has been undefined behavior in C++ for 40 years -- the kind optimizers exploit into real bugs. C++26 (P2795) reclassifies it as erroneous behavior: still a bug, still warned about, but defined, bounded, and not exploitable.

The demo poisons the stack, then reads an uninitialized int. As C++23 it prints garbage; as C++26, the same code prints a defined 0, every run. Live in your browser.

And [[indeterminate]] lets you opt back out when you really want an uninitialized buffer -- on purpose this time.

Read it: https://wrocpp.github.io/posts/erroneous-behavior/?utm_source=reddit&utm_medium=social&utm_campaign=post-erroneous-behavior

#cpp #cplusplus #cpp26 #safety #programming


r/cpp • • Dec 06 '23

Small Rant: The comma operator is one of the worst C++ design decisions I've ever seen

30 Upvotes

Today, I wrote some test code with a loop:

for (int i = 0; i < 1000; i += 1)

I wanted to increase the iterations, and remembered that C++ has a character that you can use to split a number so you can break it up and make it easier to read. I forgot what the correct character was, and used a comma:

for (int i = 0; i < 10,000; i += 1)

For those unaware, the cursed comma operator allows you to split expressinos with a comma, where the result on the left of the comma is discarded, and the result on the right is used instead. This compiled just fine. But suddenly my test code stopped running. If I didn't already know about the comma operator, it probably would have taken me way longer to realize what I'd just done.

How has this thing stayed in the language so long without revision or deprecation? What kind of masochist came up with this? Were we all just put on this earth to write C++ code and suffer? I am so close to giving this all up and starting a farm. Maybe with some goats. The fainting kind. Those adorable bug-eyed nervous wrecks would never put me through something like this.

Edit: Holy heck I came back to a lot of notifications. I didn't intend for this to be some hot take (never seen so many people in favor of the comma operator before...), but let me address some common stuff I'm seeing:

  • Yes, using a comma was silly. Commas should not be used to separate digits, and my use of one was Not Good. But in this situation, the fact that my brain blip and misuse of commas didn't create a compile time error is extremely silly.

  • Yes, I'm aware that compiler warnings exist. Apparently my team's configuration of flags turned off this warning. Regardless of why we didn't have those flags on, compiler flags like these are bandaids over the real problem: a bad language feature.

  • Yes, I'm aware that some people think comma operators are "useful" in some situations. But frankly, I've never seen a use of the comma operator that couldn't have been done some other way, or wouldn't have been better as some other kind of language feature. Any purposeful use of the comma operator should be done with something other than the comma operator. Fight me.


r/cpp • • Mar 06 '25

std::array in C++ is faster than array in C. Sometimes

Thumbnail
pvs-studio.com
0 Upvotes

r/cpp • • Dec 13 '24

C++ modules support is a joke in MSVC

0 Upvotes

I just tried to run the most basic hello world:

import std;

int main()

{

std::cout << "Hello World!\n";

}

While enabling /experimental:module

First had to fix some issues with a default console project to make it get to the crashing part.

As soon as i enable /experimental:module build errors out after these steps, without it, it compiles, but that means all experimental features are not working.

fatal error LNK1318: Unexpected PDB error; OK (0) '' with C++20 modules - Developer Community

Almost feels like 0.0% test coverage on ms side? It's experimental, but this is not even experimental quality at the moment. When can we expect a usable implementation for production use?


r/cpp • • Jun 01 '22

How dare they say ++it is faster than it++

Thumbnail
mohitmv.github.io
0 Upvotes

r/cpp • • Sep 20 '17

The C++ coding experience is bi-polar, lets talk about it

13 Upvotes

C++ has come a long way since the late 1990’s. The transition hasn’t been smooth, and young programming languages have made huge strides in the minds of new programmers.
The biggest issue facing C++ is new programmers aren’t seeking it out and the schools aren’t teaching it by default. C++ is being avoided, and honestly it probably should be. When learning how to code, understand segfaults and fighting dragons is unacceptable. C++ has become clunky and cumbersome to work with. Complexity has increased with recent changes. The only usable STL is boost or QT and the learning curve for either is large. Relevant up to date information is difficult to find, and the language still allows the user to easily do unsafe things with memory. The result is annoying crashes, constantly being forced to lookup documentation, confusion, frustration, and eventually seeking out other language solutions.

The bottom line is this, if C++ doesn’t get with the times in the next 5 years, young programmers should learn Go/rust and skip C++. This statement kills me because I love C++

There are a few core issues causing this:

  • An unwillingness to break legacy code

  • Overly complex syntax

  • Unsafe memory manipulation

  • Clunky STL

Why should we care about C++ in 2017?

C++ in the late 90’s was the best language. At the time, it provided wonderful control with unmatched syntax. No on considered memory safe languages to be a requirement, life was good. In the last 20 years computer scientist have learned a lot about libraries that lend themselves to writing faster and safer code. New players in the language wars have showed a different take on memory management. Ruby/python taught us how flexible languages can be. Javascript taught us how forgiving code can be. Rust taught us memory allocation can be safe and monitored by the compiler. The list of functional languages have taught us new ways to think about state. Today C++ isn’t the best language, there are many others which can do all the things C++ does, and in many ways, they do it better. So why do I care? Why should we care? We should care because C++ provides the performance tuning nobs that most languages hide. We should care because C++ is for elite programmers that are pushing the bounds of current hardware. We should care because C++ isn’t full of annoying annotations or vendor/platform lock-in. We should care because C++ is powerful.
C++ is worth fighting for, below are the glaring issues I see.

Breaking old code compatibility IS okay

“Changes that don’t break compatibility with existing code” is well intentioned and incorrect. Code written using C++17 or older standards is welcome to continue doing so. New code written using new standards can leverage updated behavior from existing key words. Which is worse, upset the coder with expectations that 20 year old code acts exactly the same with the newest compiler flags? Or is it worse to have droves of 20 year old programmers choose a more modern language for their new project?

Header files

Compilers have come a long way in the last 20 years. Requiring the user to write header files by hand is antiquated. There are almost no cases that should require custom written headers. The compiler should auto generate header files for each cpp file on the fly. Perhaps a new pre processor keyword needs to be created? #import “xxx.cpp” which causes the header file to be generated? With this new pre-processor, please also provide a way to explicitly state which items to include from the remote file. #import “xxxx.cpp” with foo, bar, Klass. This would include function foo, bar, and class Klass.

Overly complex or long winded syntax

No one likes auto. Var/let are well established, and don’t require the extra typing, pick one of those two and move on. I prefer var over let because I can type var with just my left hand, it feels better. C++’s lambda’s are great, but they are way too much typing. By default (x) → { code; } should translate to = → var { a thing }. Function pointers need a nicer syntax to pass themselves around. I’m not sure what is, but std:func<> isn’t right. Template syntax should be reduced to <T> added to the function or class. Users just want to write: class Dog<T> {}; or Dog<T> → int () one time and then use T inside that class/function.

Revamp of memory allocation syntax

Garbage collection is a hack, its horrible, its slow, we don’t want it. I love stack allocation. I love scoped heap allocation. I love scoped heap allocation that can transfer its ownership to another scope. I love shared pointers. In C++x11 and above, only stack allocation is a first class citizen, and all methods listed contain dragons. The “new” keyword needs to replace unique_ptr. When new is called, a scoped based unique_ptr should be created. No more make_unique<T>(xx), just var dog = new Dog(); If a unique pointer is passed to a function, the life-cycle of that pointer cannot extend the function class.
If a unique pointer is passed to a function and the life-cycle IS extended, then that pointer’s scope is extended to the scope of that new life-cycle. Perhaps there is some syntax required in the function’s parameters to make this rust like borrow behavior clearly stated? Pointer syntax is great, but its not safe. I want to use pointers, but the compiler needs to monitor my usage and ensure the pointer is treated safely. shared_ptr needs its own keyword. Perhaps “shared” which will create shared pointers. Var dog = shared Dog(); When shared pointers are used in functions, their reference count should be pinned to the lifecycle of the function they are used to avoid possible premature cleanup. Herb Sutter has a wonderful video covering a work around for this “pinning” behavior. Delete keyword should be deprecated, it would have the same effective behavior as assigning nullptr; to the pointer.

Stack safe destructors

Memory deconstruction shouldn’t happen through stack allocated function calls. As many of you know, using unique_ptr in a nested tree structure class can easily cause “random” crashing when your destructors chain together and overflow the stack buffer. Herb Sutter has a wonderful video on this behavior.
The compiler needs to come up with a different system for handling destructors that is heap based allocation and unable to crash in any reasonable programming situation. Perhaps tail recursion? Whatever the solution is, slay the dragons

co-routines (yield) and a proper foreach

Begin()/End() are very clunky to use and are not standard among other programming languages these days. The industry has decided co-routines are the preferable method to handle foreach iterators. Simply put, a “yield” like keyword, and a foreach ( var x : co-routine ) to handle it would go a long way. Python nailed this behavior. The yield/for interaction are exactly the correct model C++ needs.

Named and variable length parameters

In some cases, named parameters make reading code much more verbose. There are also times when parameter order doesn’t matter as much as name grouping: action(slope=0.5,offset=2,foo=9) is much easier to read and understand over: action( 0.5, 2, 9 ); In addition to named parameters, capturing variable length parameter lists and a hash of named parameters allows the coder a lot of flexibility. Python nails this behavior. Anyone that has written frameworks, especially web based frameworks knows this type of behavior is invaluable. When naming parameters, OR DOESN’T MATTER! The compiler is welcome to reorder my parameters for me. Named class member initialization When allocating classes, there isn’t a great way to assign member values, without extra typing by the user. Var dog = new Dog () { age: 17, color: “yellow” }; Making the class initialization compatibility with Json format, and allowing the implementation to be extendable through operatorXX is ideal.
Order of named variables doesn’t matter. The compiler should reorder as needed.

Dictionaries as first class citizens

Json rules the world. C++ should support the json format of data, which is stored into a dictionary.

Safe arrays as first class citizens

Allow the user two types of array allocation, stack and heap allocation. Stack allocation should work with variable length one time initialization (does not require a compile time constant). Many compilers already do this (g++), all of them should. Arrays is C++ should be safe by providing bounds checking and all the typical helper functions. When a user creates an array, it should be a STL class, not pointer math. Stack and heap arrays should have feature parity with each other. Arrays should provide all the functionality a vector does, except dynamically changing sizes. Strings, localization, and formats as first class citizens Var x = “something great”; should create a string class. Char arrays are accent, the default behavior shouldn’t be char arrays, their interaction should be the expection. I should be able to set string values in class member: class Dog { var Name = “Woofy”; }; Switch statements also need to support strings natively. The user should find it easy to deal with string literals. Built in string localization should be a standard feature of the compiler. When I write var name = “dog”, the compiler should auto gen a keyword lookup file. I can then go through and specify all the different languages I want to support, and when selected by the STL, those keywords instances of “dog” will be replaced with the localized word. Built in string formats. Cout is great, printf is greater, what about general string construction???? Allowing the user to write var str = “%d Bananas” << (5) is really handy. Allowing the user to write var str = “Run “ << 5 << “ times”; is also very handy.

Enums revamp

When dealing with enums, the type name should be included to give context to the reader. Reading code that says var x = COUNT is much more ambiguous than var x = Apples.COUNT;
Enums should easily be convertible into a string and from an int back into the enum. Nothing is worse than writing a switch statement of enumeration values to output nice string names. Var e = EnumVal.VALUE; (string)e; // Return “VALUE” (int)e; //Return 6?

Keep C style overload syntax with updated modern behavior

Programmers enjoy C-Style syntax casts var x = (int)a; Don’t get rid of them. Allow this syntax to play nice and have compiler checks. If that is impossible, then have the new style double { x } be more aggressive and work the way a coder would want. C++ cast syntax of dynamic_cast<XXX>(x) is way too much typing.

Compile time reflections and meta classes. sorry for saying run time, I meant compile time. Run time reflections make no sense with a language like cpp, sorry

C++ needs to provide detailed reflections. The user should be able to iterate through parameters of classes, get names of functions etc. The user should also be able to get values of parameters in classes, or even set values through reflects. Meta classes are needed, not sure what else to say there. Class initialization through a string name also needs to be implemented. Initialize.Create<BaseClass>(“MyClass”) where MyClass extends BaseClass. Hopefully it would go without saying, the syntax to accomplish this needs to be brief. The compiler should create this info at compile time.

Friendly tuples

I know C++ has tuples now, but their implementation is cumbersome. Tuples should be created by syntax akin to: var tup = (1,2,4,5) Accessing those tuples: var a = tup[0]; Tuples should have feature parity with arrays, except for being immutable.

Function decorators

Provide a way to attach symbols to the reflection system which can be accessed during run-time.
Allow the user a way to pass the calling function and its parameters into a user defined function, where any action can be taken. Wrapper function decorators are extremely helpful when writing frameworks. Anyone that has written framework libraries using python know the behavior I’m talking about.

Primitive helpers

Pay to play programming is awesome. Provide helper primitive function calls like 1.toString(); They read nice and provide a wonderful feel to the language. When implemented correctly, such a call could compile down to itoa(1);

Common names for similar STLv2 actions

Provide common names for all similar actions inside the STL. If dictionaries, arrays, and vectors all provide a “search” functionality, ensure it is called search or find in all different implements.

Functional STL, none or extremely rare use of try catch

The new STL should hopefully never throw exceptions. Return values can contain error information, requiring a user to wrap try/catch around the basic STL logic makes for ugly hard to trace code. Deep STLv2 that plays nice together

  • Array stack allocated

  • Array heap allocated

  • Vector

  • Friendly tuples

  • Dictionaries (Json)

  • String

  • Stack

  • Queue

  • File

  • Memcache

  • Sort

  • Regex

  • Random

  • MD5/Sha256

  • Tcp

  • Http/Https

  • Mutexs

  • Guids

There are many many more features the STLv2 needs to provide but here is an example. The user should feel that whatever data interaction is required, there is an easy to use library that’ll provide that functionality and do so with common names so they can guess how to use it without constantly looking up documentation.
The libraries need to smoothly work together, it should be trivial to convert data from one data structure into another.

Community owned package manager

Python has pip, ruby has gems, javascript has node, rust has cargo. C++ needs a well managed, community ran system for exchanging code.

Community owned ORM and web framework

The young kids play in the web. After all these changes are made, the C++ community needs a well designed ORM, code first migrations, and Restful web framework. The framework needs to lend itself well to working with Angular/React web calls. The web framework also needs to provide a fantastic admin interface into the database that is extremely extendable. Think rails or django.

Slay the dragons!

The user should find it difficult to crash a C++ program. The language shouldn’t be full of pitfalls, it should be a safe and joyful to use.

What can we do?

As a community we need to do one of two things: 1. Speak out and be heard. Provide solutions, contribute and get the C++ we need. 2. Speak out and be ignored, learn rust/go and continue our work.


r/cpp • • Jun 19 '26

One of the best C++29 features is already available?

Thumbnail meetingcpp.com
0 Upvotes

r/cpp • • Jul 21 '19

C++ is broken

9 Upvotes

C++ as a language is a tool for developers to productively deliver software. Language evolution is NOT the end objective in the real world.

The whole C++ ecosystem from committee to all of the conference backslapping and training is broken in this respect. It's focus is off.

Instead of 'boost' we need 'boosted' to help define, review and encourage that wider ecosystem so developers can be productive.

It's ok to define things that aren't infinitely flexible, and infinitely extensible but get the job done.

It's OK and, in some ways better, to provide an opinionated library outside the standards rather than deliver an intellectually burdened, extensible interface two years later than needed.

All the helpful features in the core language and core libraries are MEANT to enable a much wider ecosystem to make the tool that is C++ more productive.

But we aren't getting a wider ecosystem, we are just getting a language where we are apparently 'not paying for' a huge intellectual burden.

I want to say at this point that intellectually I am constantly impressed by the committee's work and standards BUT ...

The payoff just isn't happening. Even within the standards committee more time is being spent in intellectually stimulating but largely pointless activities because the tool and productivity benefits aren't happening.

Look at how the wider productive ecosystem hasn't flourished since C++ 11.

I know many excellent libraries have been made, but think about your next large project and how much is coming from a mixed bag of variable quality 3rd party libs to plug basic capabilities.

The committee work is spread so thin that core building blocks get pushed out further in time and so can't be built upon by library authors.

Networking, executors, any form of I/O - slipping again.

Lots of hard work being done but by far too few people in their spare time.

Seems a very dysfunctional way to move the monolith forward.

'You don't pay for what you don't use' is laudable up to a point, but the 'don't use' because you don't actually have, say, a basic network library is more of a reality.

That basic network lib and executor model I've been impatiently waiting for should probably not be part of the core standards remit (architectural concepts and keyword support for executors would probably be necessary, but not much else.)

If we had the metaclass generation as proposed, I'd hope even more of these items would then be able to fall outside the standards.


r/cpp • • Jan 30 '23

C++ feels like the only language I need. Prove me wrong.

0 Upvotes

r/cpp • • Oct 07 '22

coost - A fantastic C++ library

0 Upvotes

coost is an elegant and efficient cross-platform C++ base library. Its goal is to create a sword of C++ to make C++ programming easy and enjoyable.

coost is like boost, but more lightweight, the static library built on linux or mac is only about 1MB in size. However, it still provides enough powerful features:

  • Command line and config file parser (flag)

  • High performance log library (log)

  • Unit testing framework

  • go-style coroutine

  • Coroutine-based network library

  • Efficient JSON library

  • JSON RPC framework

  • Atomic operation (atomic)

  • Efficient stream (fastream)

  • Efficient string (fastring)

  • String utility (str)

  • Time library (time)

  • Thread library (thread)

  • Timed Task Scheduler

  • God-oriented programming

  • LruMap

  • hash library

  • path library

  • File utilities (fs)

  • System operations (os)

  • Fast memory allocator

Documents

Core features


God-oriented programming

co/god.h provides some features based on templates.

#include "co/god.h"

void f() {
    god::bless_no_bugs();
    god::align_up<8>(31); // -> 32
    god::is_same<T, int, bool>(); // T is int or bool?
}

flag

flag is a command line and config file parser. It is similar to gflags, but more powerful:

  • Support parameters from both command-line and config file.

  • Support automatic generation of the config file.

  • Support flag aliases.

  • Flag of integer type, the value can take a unit k,m,g,t,p.

...

#include "co/flag.h"
#include "co/cout.h"

DEF_bool(x, false, "x");
DEF_bool(debug, false, "dbg", d);
DEF_uint32(u, 0, "xxx");
DEF_string(s, "", "xx");

int main(int argc, char** argv) {
    flag::init(argc, argv);
    COUT << "x: " << FLG_x;
    COUT << "y: " << FLG_y;
    COUT << "debug: " << FLG_debug;
    COUT << "u: " << FLG_u;
    COUT << FLG_s << "|" << FLG_s.size();
    return 0;
}

In the above example, the macros start with DEF_ define 4 flags. Each flag corresponds to a global variable, whose name is FLG_ plus the flag name. The flag debug has an alias d. After building, the above code can run as follow:

./xx                  # Run with default configs
./xx -x -s good       # x -> true, s -> "good"
./xx -debug           # debug -> true
./xx -xd              # x -> true, debug -> true
./xx -u 8k            # u -> 8192

./xx -mkconf          # Automatically generate a config file: xx.conf
./xx xx.conf          # run with a config file
./xx -conf xx.conf    # Same as above

log

log is a high-performance log library, some components in coost use it to print logs.

log supports two types of logs: one is level log, which is divided into 5 levels: debug, info, warning, error and fatal, printing a fatal log will terminate the program; the other is topic log, logs are grouped by topic, and logs of different topics are written to different files.

#include "co/log.h"

int main(int argc, char** argv) {
    flag::init(argc, argv);

    TLOG("xx") << "s" << 23; // topic log
    DLOG << "hello " << 23;  // debug
    LOG << "hello " << 23;   // info
    WLOG << "hello " << 23;  // warning
    ELOG << "hello " << 23;  // error
    FLOG << "hello " << 23;  // fatal

    return 0;
}

co/log also provides a series of CHECK macros, which is an enhanced version of assert, and they will not be cleared in debug mode.

void* p = malloc(32);
CHECK(p != NULL) << "malloc failed..";
CHECK_NE(p, NULL) << "malloc failed..";

log is very fast, the following are some test results:

platformglogco/logspeedup
win2012 HHD1.6MB/s180MB/s112.5
win10 SSD3.7MB/s560MB/s151.3
mac SSD17MB/s450MB/s26.4
linux SSD54MB/s1023MB/s18.9

The above is the write speed of co/log and glog (single thread, 1 million logs). It can be seen that co/log is nearly two orders of magnitude faster than glog.

threadslinux co/loglinux spdlogwin co/logwin spdlogspeedup
10.0872352.0761720.1177040.46115623.8/3.9
20.1831603.7293860.1581220.51176920.3/3.2
40.2067124.7642380.3166070.74322723.0/2.3
80.3020883.9636440.4060251.41738713.1/3.5

The above is the time of printing 1 million logs with 1, 2, 4, and 8 threads, in seconds. Speedup is the performance improvement of co/log compared to spdlog on linux and windows platforms.

unitest

unitest is a simple and easy-to-use unit test framework. Many components in coost use it to write unit test code, which guarantees the stability of coost.

#include "co/unitest.h"
#include "co/os.h"

namespace test {
    
DEF_test(os) {
    DEF_case(homedir) {
        EXPECT_NE(os::homedir(), "");
    }

    DEF_case(cpunum) {
        EXPECT_GT(os::cpunum(), 0);
    }
}
    
} // namespace test

The above is a simple example. The DEF_test macro defines a test unit, which is actually a function (a method in a class). The DEF_case macro defines test cases, and each test case is actually a code block. The main function is simple as below:

#include "co/unitest.h"

int main(int argc, char** argv) {
    flag::init(argc, argv);
    unitest::run_all_tests();
    return 0;
}

The directory unitest contains the unit test code in coost. Users can run unitest with the following commands:

xmake r unitest      # Run all test cases
xmake r unitest -os  # Run test cases in the os unit

JSON

In coost v3.0, Json provides fluent APIs, which is more convenient to use.

// {"a":23,"b":false,"s":"123","v":[1,2,3],"o":{"xx":0}}
Json x = {
    { "a", 23 },
    { "b", false },
    { "s", "123" },
    { "v", {1,2,3} },
    { "o", {
        {"xx", 0}
    }},
};

// equal to x
Json y = Json()
    .add_member("a", 23)
    .add_member("b", false)
    .add_member("s", "123")
    .add_member("v", Json().push_back(1).push_back(2).push_back(3))
    .add_member("o", Json().add_member("xx", 0));

x.get("a").as_int();       // 23
x.get("s").as_string();    // "123"
x.get("s").as_int();       // 123, string -> int
x.get("v", 0).as_int();    // 1
x.get("v", 2).as_int();    // 3
x.get("o", "xx").as_int(); // 0

x["a"] == 23;          // true
x["s"] == "123";       // true
x.get("o", "xx") != 0; // false
osco/json stringifyco/json parserapidjson stringifyrapidjson parsespeedup
win569924208924953.6/2.7
mac7831097128916581.6/1.5
linux468764135910702.9/1.4

The above is the average time of stringifying and parsing minimized twitter.json, in microseconds (us), speedup is the performance improvement of co/json compared to rapidjson.

Coroutine

coost has implemented a go-style coroutine, which has the following features:

  • Support multi-thread scheduling, the default number of threads is the number of system CPU cores.

  • Shared stack, coroutines in the same thread share several stacks (the default size is 1MB), and the memory usage is low.

  • There is a flat relationship between coroutines, and new coroutines can be created from anywhere (including in coroutines).

  • Support coroutine synchronization events, coroutine locks, channels, and waitgroups.

...

#include "co/co.h"

int main(int argc, char** argv) {
    flag::init(argc, argv);

    co::WaitGroup wg;
    wg.add(2);

    go([wg](){
        LOG << "hello world";
        wg.done();
    });

    go([wg](){
        LOG << "hello again";
        wg.done();
    });

    wg.wait();
    return 0;
}

In the above code, the coroutines created by go() will be evenly distributed to different scheduling threads. Users can also control the scheduling of coroutines by themselves:

// run f1 and f2 in the same scheduler
auto s = co::next_scheduler();
s->go(f1);
s->go(f2);

// run f in all schedulers
for (auto& s : co::schedulers()) {
    s->go(f);
}

network programming

coost provides a coroutine-based network programming framework, which can be roughly divided into 3 parts:

  • coroutineized socket API, similar in form to the system socket API, users familiar with socket programming can easily write high-performance network programs in a synchronous manner.

  • TCP, HTTP, RPC and other high-level network programming components, compatible with IPv6, also support SSL, it is more convenient to use than socket API.

  • System API hook, with which, third-party network libraries can be used directly in coroutines.

RPC server

#include "co/co.h"
#include "co/rpc.h"
#include "co/time.h"

int main(int argc, char** argv) {
    flag::init(argc, argv);

    rpc::Server()
        .add_service(new xx::HelloWorldImpl)
        .start("127.0.0.1", 7788, "/xx");

    for (;;) sleep::sec(80000);
    return 0;
}

rpc::Server also supports HTTP protocol, you may use the POST method to call the RPC service:

curl http://127.0.0.1:7788/xx --request POST --data '{"api":"ping"}'

Static web server

#include "co/flag.h"
#include "co/http.h"

DEF_string(d, ".", "root dir"); // docroot for the web server

int main(int argc, char** argv) {
    flag::init(argc, argv);
    so::easy(FLG_d.c_str()); // mum never have to worry again
    return 0;
}

HTTP server

void cb(const http::Req& req, http::Res& res) {
    if (req.is_method_get()) {
        if (req.url() == "/hello") {
            res.set_status(200);
            res.set_body("hello world");
        } else {
            res.set_status(404);
        }
    } else {
        res.set_status(405); // method not allowed
    }
}

// http
http::Server().on_req(cb).start("0.0.0.0", 80);

// https
http::Server().on_req(cb).start(
    "0.0.0.0", 443, "privkey.pem", "certificate.pem"
);

HTTP client

void f() {
    http::Client c("https://github.com");

    c.get("/");
    LOG << "response code: "<< c.status();
    LOG << "body size: "<< c.body().size();
    LOG << "Content-Length: "<< c.header("Content-Length");
    LOG << c.header();

    c.post("/hello", "data xxx");
    LOG << "response code: "<< c.status();
}

go(f);

r/cpp • • May 23 '24

Is MacBook good for C++ developer?

3 Upvotes

Hi. I am a C++ developer, and I write code for both Linux and Windows, depending on the project. Currently, in my country (I'm from Ukraine), there are frequent power outages (3 hours with power, 4 hours without, and so on), and I am looking for a laptop with a long-lasting battery. Since MacBooks have excellent battery life, I am considering buying one, but I have a few questions.

Will I experience a significant loss in performance when building a C++ project in Docker using an x64 Ubuntu image and the Rosetta emulator?

Will there be a noticeable drop in performance if I use x64 Windows through an emulator?

Is it worth making these sacrifices, or should I buy a Windows laptop with a less impressive battery?

I have a powerful PC that I’m using for work, and I can use It for building projects, but when the power is on.


r/cpp • • Aug 24 '22

Why the hell are headers still a thing after all these years?!

1 Upvotes

I've seen C++ some twenty-a-lot years ago and was looking into some more performance driven stuff for a possible personal project and... Why the hell are headers still a thing after all these years?!

I mean... Things changed a lot. I barely recognize a lot of C++ and some might be related to fading memory, but a bog lot have just changed. I wonder if is there anything headers are the perfect solution to. So it's just hellish bureaucracy?

As I probably don't know what I'm talking about anymore, I'm open to be convinced otherwise.

PS: I know it ain't the best place to ask, but I do accept suggestions for languages platform to write some fast code for Windows and mobile platforms.


r/cpp • • Dec 19 '23

Obsessed with {} initialization?

4 Upvotes

I'm on a discord where everyone seems to be obsessed to use brace initialization everywhere.
My motto is: Use things rarely, only when needed, to express that right there the feature does something important.
Personally I would completely advocate against using it for simple stuff like
double tax{0.09*price};

or just int{0}

probably a hornets nest


r/cpp • • May 12 '15

Criticizing the Rust Language, and Why C/C++ Will Never Die

Thumbnail
viva64.com
0 Upvotes

r/cpp • • Aug 17 '23

I Don't Use Exceptions in C++ Anymore

Thumbnail thelig.ht
0 Upvotes

r/cpp • • Feb 13 '24

Prevent or warn on usage of std::map []?

6 Upvotes

The default insertion of a value when std::map [] doesn't find a value for the key has to be one of the worst decisions in STL history (which is kind of impressive.) At work over the last year or so, we've had at least four, maybe five, bugs caused by this. It's so easy to do without thinking about it, and so easy to miss in a code review. And some of them had been there for many years and finally caused an issue, so no one was even looking for them.

Is there any way to prevent its use, or at least to warn on its use in MSVC? We use the built in static analyzer, and I don't see any warning related to that, though there are a lot of them and I may have missed something.


r/cpp • • Oct 15 '13

C++ has become a scripting language

Thumbnail voices.canonical.com
1 Upvotes

r/cpp • • Jan 09 '24

A hard quiz to crack for C++ programmers by Sergei Kushnirenko

Thumbnail
pvs-studio.com
0 Upvotes

r/cpp • • Jun 23 '18

East const Central

Thumbnail
slashslash.info
0 Upvotes

r/cpp • • Apr 08 '25

Beware when moving a `std::optional`!

Thumbnail blog.tal.bi
0 Upvotes

r/cpp • • May 09 '21

Why do people say CLion is great?

0 Upvotes

I've tried to use CLion but to be honest, it's been a pain in the ass. It's very slow. But it's not even my point. To run a simple "Hello World" it's a whole issue. I really don't like this "cmake" thing or it creating a ton of auxiliary files and folders.

I tried to use the "single file execution" plugin but it still requires some auxiliary files.

Do you guys know something I can do to use it just as an ordinary IDE? Just code completion and its hints. I really like them but de "additionals" destroy the IDE for me.


r/cpp • • Nov 08 '23

make_shared is more effective that standard shared_prt

0 Upvotes

Today I have learned an interesting fact about shared_ptr. It turns out that make_shared is more effective that standard shared_ptr init due to several reasons:

  • less memory allocations (std::make_shared performs one heap-allocation, whereas calling the std::shared_ptr constructor performs two)

  • better exception safety (using make_shared means that you don't need to deal with new and raw pointers at all)

Here is more information on this topic: https://stackoverflow.com/questions/20895648/difference-in-make-shared-and-normal-shared-ptr-in-c.


r/cpp • • Jan 16 '13

Are the Java vulnerabilities actually C and C++ vulnerabilities?

Thumbnail
isocpp.org
1 Upvotes

r/cpp • • Jan 29 '17

A Guide to Porting C and C++ code to Rust

Thumbnail locka99.gitbooks.io
0 Upvotes