🍌 C++ Feed
306 subscribers
218 photos
12.7K links
Агрегатор всего подряд про C++.

Для связи: @smertig

Powered by https://github.com/Smertig/banana
Download Telegram
C++
Potential way to solve dangling reference to temporary?

When I am writing when() in SugarPP, I kept wondering how to deal with returning reference of possibly lvalue references and rvalue reference. To make it simpler, it's the same as cpp int x{}; auto&& bigger = std::max(x, -1); //... Use bigger, OK, but dangling if -1 is bigger I gave up by just return by value. But it's obviously not optimal if I also want to be able to modify through the reference (both the lvalue or the temporary), as if the temporary is also lvalue. Of course I can just give it a name to trivially solve it but still it's amazingly unintuitive. What if the compiler can implicitly generate a name to make the temporary to a lvalue when the function accepts reference (because temporary will still "materialize" anyway) at the current calling scope, but still interpret it as rvalues like this: cpp int x{}; int __temp = -1; auto&& bigger = std::max(x, std::move(__temp)); //... Use bigger, OK now submitted by /u/HO-COOH
[link] [comments]
C++ – Типизированный язык программирования
Тестирование приложений в условиях нехватки памяти

Вопрос о том надо ли проверять то, что возвращает malloc является спорным и всегда порождает жаркие дискуссии.

Часть людей считает, что надо пытаться обрабатывать все виды runtime ошибок, в т.ч. и OOM ситуации. Другие считают, что с OOM всё равно мало что можно сделать и лучше дать приложению просто упасть. На стороне второй группы людей ещё и тот факт, что дополнительная логика обработки OOM с трудом поддаётся тестированию. А если код не тестируется, то почти наверняка он не работает.

Я полностью согласен с тем, что не стоит реализовывать логику обработки ошибок которую вы не собираетесь тестировать. Почти наверняка она ничего не улучшит, а может и того хуже — всё испортит.

Вопрос о том надо ли пытаться обрабатывать OOM ситуации в библиотеках/приложениях является противоречивым и мы не будем его здесь касаться. В рамках данной публикации я лишь хочу поделиться опытом того как можно тестировать реализованную логику обработки OOM ситуаций в приложениях написанных на C/C++. Разговор будет идти об операционных системах Linux и macOS. Ввиду ряда причин, Windows будет обойдён стороной. Читать дальше →
C++ – Типизированный язык программирования
Релиз акторного фреймворка rotor v0.09 (c++)

rotorненавязчивый С++ акторный микрофремворк, похожий на своих старших братьев — caf и sobjectizer. В новом релизе внутреннее ядро полностью было переделано с помощью механизмов плагинов, так что это затронуло жизненный цикл акторов. Читать дальше →
C++
Want To Chat C++? Join The Best Technical C++ Chat Community!

If you would like to chat with other C++ engineers, get help on C++ topics, or participate and learn about the latest developments in the C++ Standard, there's a great place for you! It is called the Cpplang Slack and you can get a free invite here: https://cppalliance.org/slack Be sure to check out our #learn channel for answers to common C++ questions! This is the place to go if you want robust, technical C++ discussion without the politics! Please abide by our Acceptable Use Policy: https://cppalliance.org/slack/ submitted by /u/VinnieFalco
[link] [comments]
C++
Tips for debugging C++ code?

It's been years since I had a C++ job. I got back into it recently and finally hit a wall on debugging a problem. What are your techniques on debugging C++ problems? submitted by /u/Quiet-Smoke-8844
[link] [comments]
C++
Bjarne Stroustrup on "dead bodies of type theorists"

I can't produce a link off the top of my head, but I remember Bjarne Stroustrup saying (on a few occasions, in a talk or a panel) that "non-type template parameters were introduced in C++ over the dead bodies of some type theorists" (quote from memory). This surprises me since types depending on values is a fundamental concept in Martin-Löf type theory which is older than C++. Does anyone have any knowledge on what feedback Bjarne Stroustrup received from type theorists? submitted by /u/dylanzdavies
[link] [comments]
C++ – Типизированный язык программирования
[Из песочницы] Кривые Безье. Немного о пересечениях и как можно проще

Article

Вы сталкивались когда-нибудь с построением (непрерывного) пути обхода кривой на плоскости, заданной отрезками и кривыми Безье?

Вроде бы не сильно сложная задача: состыковать отрезки кривых в один путь и обойти его "не отрывая пера". Замкнутая кривая обходится в одном направлении, ответвления — в прямом и обратном, начало и конец в одном узле.

Всё было хорошо, пока из-под рук дизайнеров не стали вылезать монструозные пути, где отдельные кривые могли пересекаться или не точно состыковываться. Объяснение было предельно простым — визуально они все лежат как надо, а для станка, который этот путь будет обходить, такие отклонения незаметны.

Вооружившись знанием о величине максимально допустимого отклонения, я приступил к исследованию, результатами которого хочу поделиться. Читать дальше →
Arthur O’Dwyer
A very short war story on too much overloading

On my previous post
“Inheritance is for sharing an interface (and so is overloading)” (2020-10-09),
a couple of Reddit commenters expressed disbelief at my third section, where I claimed that the
vector::erase overload set was poorly designed. They had never run into the common bug

// Oops!
v.erase(
std::remove_if(v.begin(), v.end(), isOdd)
);


For more on erasing from STL containers, see “How to erase from an STL container” (2020-07-08).

Here’s another example of grief caused by overuse-of-overloading, which I just ran into at work last week.

class mgr_t : public asio_actor {
~~~
virtual std::string getname() const = 0;
virtual result_t subscribe(actor::ptr tgt, msghandler handler,
priority::level prio, const std::string type,
bool enrich = false) = 0;
virtual result_t subscribe(actor::ptr tgt, msghandler handler,
priority::level prio, selector f, unsigned &id,
bool enrich = false) = 0;
virtual result_t subscribe(actor::ptr tgt, msghandler handler,
priority::level prio,
bool enrich = false) = 0;
virtual void subscribe_connect(actor::ptr tgt, connhandler handler,
priority::level prio) = 0;
virtual void subscribe_disconnect(actor::ptr tgt, connhandler handler,
priority::level prio) = 0;
~~~
};


And then there’s a caller in some other repository that does this:

this->message_ = std::string("subscription failed");
return g_mgr->subscribe(ctl_actor::instance(), stats,
priority::level::high, std::string("queue-stats"));


You might look at those lines and think: Ah, the casts to std::string are redundant. This is just
a Java programmer’s attempt to keep track of where “string objects” are created. I can remove them.

You’d be right about the first cast, but it turns out you’d be wrong about the second!

return g_mgr->subscribe(ctl_actor::instance(), stats,
priority::level::high, std::string("queue-stats"));


is a call to mgr_t::subscribe(actor::ptr, msghandler, priority::level, const std::string, bool = false). But

return g_mgr->subscribe(ctl_actor::instance(), stats,
priority::level::high, "queue-stats");


is a call to mgr_t::subscribe(actor::ptr, msghandler, priority::level, bool = false)!
Because "queue-stats", after decaying to const char*, would rather implicitly convert
to the built-in type bool than to the user-defined type std::string. (Godbolt.)

The above snippet exemplifies many sins which I’ve previously discussed on this blog. See:



“Default function arguments are the devil” (2020-04-18)


const is a contract” (2019-01-03) re the missing ampersand


“PSA: shared_ptr() is not make_shared()” (2019-03-06) re actor::ptr


And of course it should be using the Non-Virtual Interface idiom, but I haven’t got a blog post
dedicated to that subject, yet. See
“CppCon 2019 talks are up” (2019-10-18).



Nevertheless, I think the primary sin here — or at least the “first among equals
— is that it has three overloads of subscribe, doing radically different things with (s
C++
CppCon 2020 presentation recommendations?

I've seen four videos so far and I can only recommend one of them as being interesting and/or well presented: The Many Shades of reference_wrapper - Zhihao Yuan - CppCon 2020 Do you guys have recommendations? submitted by /u/lookatmetype
[link] [comments]
C++
Awkward passing of Allocators and Schedulers to C++20 Coroutines

C++20 coroutines are here and give us some really intersting functionality. When working on library code I've encountered inelegance in the following: PMR allocators to a coroutine not practical because you cannot access arguments provided to coroutines. Seems like get_return_object could be provided with the function arguments, anybody see problems with that? Passing ordinary allocators to coroutines constructable just like containers: ​ constexpr vector( size_type count, const T& value, const Allocator& alloc = Allocator()); Passing various worker queues to different coroutines without singleton or global data. I'm interested in making a proposal to resolve some of my concerns with coroutines.Getting opinions from the community is really important to me. Finding out I'm wrong about a problem is even more important... Hope people don't mind a few of these related posts. Are others finding the same issue as me?Is this something people want? I'll keep adding to this list: Idea 1: Provide function arguments to get_return_object Pros: Could grab an allocator/queue/whatever from here. Could use this for logging and instrumentation. Could just be an additional overload avaliable for get_return_object. Cons: Provided arguments could be mutated, this might lead to confusing situations. submitted by /u/Seppeon
[link] [comments]
Modernes C++ - ModernesCpp.com
C++20: Extend std::format for User-Defined Types

Peter Gottschling presented in his last post "std::format in C++20" the basics to the new formatting library in C++20. In today's post Peter writes about the formatting of user-defined types.
Bartek's coding blog
Increased Complexity of C++20 Range Algorithms Declarations - Is It Worth?

With the addition of Ranges and Concepts in C++20, our good old algorithm interfaces got super long “rangified” versions. For example, copy is now 4 lines long… and it’s just the declaration! template std::weakly_incrementable O>
requires std::indirectly_copyable, O>
constexpr ranges::copy_result, O>
copy(R&& r, O result);
How to decipher such a long declaration? What benefits do we get instead? Is it worth it? Let’s find out. Read more...
C++
std::i/ostream's are a bit too oversized for both usage and implementation. Are there lighter alternatives widely used?

Disclaimer: I'm not solving any specific production case. Standard input/output stream specifications include a lot of details - locales, buffering, large set of virtual functions. And they're known for their performance implications. So I was wondering if there's some simpler version of i/o interface, coming from some 3rd party library, which is widely used. Something like this: struct reader { virtual std::size_t read(std::span buffer) = 0; } struct writer { virtual std::size_t write(std::span buffer) = 0; virtual void flush() = 0; } Or does everyone either just use std::i/o stream's or reimplements concept above from scratch? submitted by /u/target-san
[link] [comments]