We use forward declaration when possible, only include things that we actually use (as best as humanly possible), use precompiled headers, and a unity build.
We use FastBuild to manage the unity build process on Windows and the fact it builds as a unity in combination with how we do templates means extern template is virtually useless to us and gave zero improvements when I tested it on some heavily-used template classes we have.
Specifically; most of our heavily-used templates are explicitly instantiated in the cpp because they have some non-header-usable functions (typically saving/loading). That alone is basically what extern template does and so we already benefited from it before it was even a thing.
However, with all that said; the single biggest gain we ever got around compilation was the day we removed Boost from our codebase
Effective Modern C++: 42 Specific Ways to Improve Your Use of C++11 and C++14
IMHO, the best book for understanding C++11/14.
I respectfully disagree with a couple of these recommendations. I thought Code Complete 2 was a waste of time - I remember it saying nothing that hadn't been said better elsewhere, and it contained many statements that I thought were howlingly wrong. My memories of Modern C++ Design are fuzzy - I probably read it too early, but I recall that it seemed very complicated with dated techniques. I managed to become a professional metaprogrammer without being influenced by it in any significant way. I could read it again and offer a coherent review, but that would be time-consuming.
The Effective and Exceptional series helped me enormously (Effective STL especially).
Folks interested in this should really look at Stepanov's EoP, which has the algorithms we actually use.
For example our implementation use the triple reverse version for random access iterators.
This is a very complicated question. For a comparison, you can see http://clang.llvm.org/comparison.html although it's fairly old. It does give an indication of many of the reasons the project was started. GCC switching to GPLv3 is a major reason (same with libc++ vs libstdc++).
As for popularity, the reason is:
At this point, there's also a lot of momentum since it's the default compiler for iOS & OSX development, & really the only one unless you're building GCC yourself. Additionally, Google is investing heavily in it as well due to the modular architecture, meaning they can build tools to process C/C++ code on an automated large scale.
GCC has been making strides in making itself competitive (switching to C++, trying to make itself more modular, etc).
GCC currently is more portable than Clang (Windows support being the major hole currently in clang) & more popular in the Linux world. Clang is popular on BSD.
GCC or clang are both great for C++ development as they are conforming C++14 implementations. Visual Studio is a little bit lagging but it's catching up. I would choose the default toolchain for the platform you are on. On Linux, GCC. On OSX (& most/all BSD variants) clang. On Windows, Visual Studio.
Amazon link: C++ Templates: The Complete Guide (2nd Edition) (non-referral)
I see your point - this is one of the least effective “hey buy this thing” pages I’ve ever seen. However, I have approved this post as non-spam, as this is Josuttis’s own site (I checked whois, after noticing the typoed copyright at the bottom) and he is a Committee member. More importantly, his 1st edition coauthored with Vandevoorde was one of the books that was invaluable to my learning. Being partially responsible for my career earns him the benefit of the doubt.
Nico just needs more effective web design (I sympathize since I don’t know how to web either, it’s just that my website intentionally doesn’t try to make money in any way). Also HTTPS.
> Even if fd in C is a fairly common abbreviation for file descriptor, I would argue that making a longer, more descriptive identifier doesn't take anything away from anyone (other than the 6 unique character limit you mentioned). However, abbreviating it does take away from someone who is not a seasoned C developer, like me for example. I didn't know what fd was. I had to spend a while trying to find out what it was since I've never seen fd anywhere.
That's a pretty common complaint from newcomers, but it tends to fall away over time.
Kerninghan and Pike, who were heavily involved in the creation of UNIX and very influential to its style, wrote a book called The Practice of Programming, and had this to say about naming:
> Global functions, classes, and structures should also have descriptive names that suggest their role in a program. By contrast, shorter names suffice for local variables; within a function, n may be sufficient, npoints is fine, and numberOfPoints is overkill. Local variables used in conventional ways can have very short names. The use of i and j for loop indices, p and q for pointers, and s and t for strings is so frequent that there is little profit and perhaps some loss in longer names. Programmers are often encouraged to use long variable names regardless of context. That is a mistake: clarity is often achieved through brevity.
People coming from other languages, especially Java-style ones, will likely disagree and find this alien, but at this point UNIX style is what it is, so you tend to get used to it.
I am gladly waiting for some contributors for my RSS Guard - relatively well-known multi-protocol and multi-account feed reader with sync. Used by 2 000 - 10 000 regular users.
I strive to use simple and clean C++, but do not laugh me, some code is actually quite ugly.
The app is well-separated (lib + executable), relatively modular, well-managed. Easily compilable, no crazy dependencies which need manual installation etc. - Windows, Mac OS X (which needs maintainer badly) and Linux.
It's Herb Sutter's pet project, not an official MS thing. He spent a while talking about why he thinks it's important in his keynote at GoingNative 2013.
That's a classic book. The authors are sometimes called the Gang of Four. A lot of the patterns are really old, and aren't used much anymore or are very niche. While reading the book it can be hard to separate those patterns from the patterns that are still commonly used today.
Of the design patterns books I've read, I like Head First Design Patterns best. It is very approachable, and uses modern techniques. Most of the examples are in Java, but that doesn't matter. Good OO design patterns work in any OO language.
As for whether you should use a raw pointer or a shared pointer, that's not really an issue addressed in a design patterns book. Design patterns tend to focus on the bigger picture of the design and not on the finer details. If you want a book that goes into those details you may want a book more like Effective Modern C++.
I think I qualify as a professional template metaprogrammer, being the author of Boost.MultiIndex, a library which lets the user specify a container as a composition of indices with very rich compile-time configuration options.
C++ TMP is admittedly hard to grok (somewhat less so now with variadic templates, which considerably simplify dealing with one of the most cumbersome aspects of TMP, namely type lists), but more because of the contrived syntax than the underyling complexity per se.
To me, the most rewarding aspect of TMP is how you can increase with it the amount of compile-time intelligence so as to provide the user with terse, powerful interfaces where all this internal trickery is not exposed. This is the "magic" of TMP that appeals to both users and lib programmers alike, IMHO.
I think enums are the wrong tool for the job here the fact that C enums allow for ORing is just a distraction, why not just:
namespace flags { constexpr int a=1, b=1<<1, c=1<<2; }
auto a=flags::a | flags::b;
At the end of the day you aren't enumerating anything, you are "orring" named constant integers, so why not use them?
Boost.Program_Options if I already use boost. All other cases, it's this header-only library: cxxopts.
This is generally what is called blogspam. It's just a pointer to a youtube reupload of a GoingNative 2013 talk.
Here is the real link: Bjarne Stroustrup - The Essence of C++: With Examples in C++84, C++98, C++11, and C++14, where you can download the video directly to your computer and watch at your leisure. There are also a handful of relevant comments below the video.
The rest of the GoingNative 2013 videos are also available.
The reason is that C++ derives its declaration syntax from C. In C, there is a philosophy that the declaration should mimic use. Suppose you have a pointer to int
named x
. To deference x
, you would write *x
. Therefore, the definition is
int *x;
because the expression *x
is of type int
. This could be just as equally defined
int (*x);
The *
operator is applied to the variable, not appended to the type. This is flexible and nestable, if not particularly readable. For instance, C has pointers to functions. To call a pointer to function f
, you (in theory) write (*f)(1, 2)
. So the definition is
int (*f)(int, int);
More examples can be found in Section 5.12 of The C Programming Language.
C++ took this syntax and grafted references onto it. The problem is that there is no syntax for using a reference; they're completely invisible. So C++ made up the symbol &
to represent a reference. But it's a prefix operator, just like *
, so it's applied to the variable in the definition. Therefore, if y
is a reference to int
, it's defined
int &y;
or equivalently
int (&y);
In hindsight, it was seen that having declarations mimic usage was not the best way to go. The Go programming language, for example, behaves as you were expecting and applies the pointer marker (I think it was *
) to the type.
Edit: TL; DR: In C, and C++ by extension, declaration mimics use.
http://channel9.msdn.com/Events/GoingNative/GoingNative-2012/Clang-Defending-C-from-Murphy-s-Million-Monkeys is the URL you should have posted. You don't need a link shortener to post a link like this. Good video and discussion anyway.
I am a library author. The problem with your request is that warnings "up there" (i.e., higher levels) are at best questionable and at worst utter nonsense. Such warnings can usually be fixed either by uglifying the source code (adding extra casts, unnecessary calls, etc) or by suppressing such warnings if the compiler supports this. Sometimes, however, it is simply impossible to get rid of a warning. The now famous example of this case is the "base class should be explicitly initialized in the copy constructor" warning in GCC:
struct base { base (); base (const base&); };
struct derived: base { derived (const derived&) { } };
g++ -W -c test.cxx test.cxx: In copy constructor ‘derived::derived(const derived&)’: test.cxx:9:3: warning: base class ‘struct base’ should be initialized in the copy constructor [-Wextra]
While in this case it is easy to suppress by adding an explicit default constructor call, there are cases where this is not possible (for details see the bug report for this warning). There is also no mechanism in GCC prior to 4.6 to selectively suppress this warning.
Dear god don't listen to the people suggesting code::blocks.
It's like suggesting people learn C++98, because the default installer has yet to ship a compiler that properly supports C++11 last i used it some years back.
Teach them how to use https://godbolt.org/, with a code/execution view.
Take https://www.jetbrains.com/clion/, if you think they really need an IDE.
Just don't even think of telling them to use code::blocks!
CppCon 2015: Kate Gregory “Stop Teaching C"
This is a great video from last year's CppCon where Gregory talks about how NOT to teach C++. She doesn't refer specifically to C++ Primer Plus, but that book embodies pretty much everything she argues against. Great video, well worth checking out.
You're going to incur the structure padding one way or another due to the alignment of the larger type: http://ideone.com/ubKV6Z
The reason for not having a special templated version for types with a sentinel value is because the whole point of optional is to avoid sentinel values -- if sentinel values solve the problem then there's no reason to use optional.
"It was just like some ancient electricity-powered computer; it didn't matter how fast, error-free, and tireless it was, it didn't matter how great a labor-saving boon it was, it didn't matter what it could do or how many different ways it could amaze; if you pulled its plug out, or just hit the off button, all it became was a lump of matter; all its programs became just settings, dead instructions, and all its computations vanished as quickly as they'd moved. It was, also, like the dependency of the human-basic brain on the human-basic body; no matter how intelligent, perceptive and gifted you were, no matter how entirely you lived for the ascetic rewards of the intellect and eschewed the material world and the ignobility of the flesh, if your heart just gave out... That was the Dependency Principle; that you could never forget where your off switches were located, even if it was somewhere tiresome." - Iain M. Banks, Excession
As far as add-ons go Visual Assist is fantastic.
It has abilities like toggling between .h/.cpp files, going to the declaration/definition of a function from anywhere it is used, etc.
It also has powerful refactoring tools like renaming functions/classes, adding/removing function arguments, stubbing out definitions based on declarations, etc.
I would strongly recommend to use asio or its boost version. It is on its way to standard, so I consider it to be a choice by default, and one should have strong reasons to use something else for network stuff.
Roku is looking for great C++ developers with experience in embedded devices, video, and Linux. We've got senior positions open in Saratoga, CA, Austin, TX, and Cambridge, UK. See https://www.roku.com/about/jobs for details. I've been on the firmware team working on our Roku TV devices for the last year and a half here in the Austin office, and it's been really interesting. We've been upgrading our codebase from C++ '03/Boost to C++ '14, so I've been able to work with a lot of the new features.
This just seems like flamebait, starting from the unfounded assertion of "In theory, the two languages should be equivalent." No, C does not have templates and thus it's much harder to get the degree of inlining that C++ and its standard library is able to achieve. If you compare std::sort()
with qsort()
there's a definite difference.
And then it goes on to deconstruct this strawman of the non-intrusive linked list container. Well, if you want an intrusive linked list in C++ (i.e. one that works just like the C version with the links as part of the node) you can do that too. Boost has a very rich library of intrusive containers of all kinds including singly and doubly linked lists. The standard library one is non-intrusive because it offers maximum flexibility, but you don't have to use it -- after all, the comparison is against hand-coded C so "it's not in stdlib" cannot possibly be a strike against C++.
And then there's some preposterous assertion that item erasure is always O(n) using std::list
, but it's not. You can call std::list::erase()
on an iterator pointing at the item you want to erase and it's O(1), just like the C example. You can even keep on iterating by saving the return value, because only the iterators of the deleted items are invalidated.
I can't fathom how anyone that claims to know C++ would write this drek.
> Head First Design Patterns
I like that book very much too, but it's a bit too OO-heavy. Just keep in mind that (Modern) C++ is not a purely OO language and has many other techniques - generic programming, free functions, etc. You can't just translate the Java code 1:1 to C++ and get good C++ code. C++ can do much more. With that in mind, it's a great book.
Read Effective Modern C++ in addition to that, watch some GN/CppCon talks, and you're good to go.
When I first read about branch prediction on SO years ago, I realized there was a whole world of optimizations I wasn't aware of, optimizations which are basically undiscoverable.
I can fire up a profiler and find hot paths that are easy to diagnose and fix. This function is called a million times? I didn't expect that. Let's inline it or use a lookup table. Why is this call red? Oh, it's allocating on the heap, let's get rid of that.
But when I see a simple red loop, I come to the conclusion "welp, there's nothing more I can do here, it's as simple as it gets".
for (unsigned c = 0; c < arraySize; ++c) { if (data[c] >= 128) sum += data[c]; }
How on earth am I supposed to know that sorting the array, changing the if
to bit fiddling, or even just interchanging the loops could give me a ten-fold speed increase? Well, now I know that, but there are hundreds of other optimizations (macro optimizations) that I will never be able to figure out. And it just gets worse as processors get better.
I would suggest reading the stackoverflow book list on the topic and picking ones that suit your background (you don't give us any info to go on).
> I'm quite sure GPL licenced code can be incorporated into GCC standard library
The GCC Runtime Library Exception (http://gcc.gnu.org/onlinedocs/libstdc++/manual/license.html) means that's false for general GPL code.
This is what constexpr
is for! This keyword would in this case allow the compiler to compute your table at compilation time and write it directly into the binary.
> In your work avoid static variables at function level – they are bad practice anyway
And the answer is instead to use top-level singletons? No thank you!
The Meyer's singleton - more or less the original solution in the article - is a well-known solution that avoids many of the issues of top-level singletons. And if you use constexpr
, it's very likely that this won't involve any branching at runtime.
You might be right in general, but as literally all i do day in / day out is write custom UI applications in C++, I obviously have a hard time seeing it this way.
I should mention that there is a massive community who do similar work to what I do, often centred around the so-called "creative coding" (ugh, I hate that term) toolkits such as cinder and openFrameworks.
Perhaps if you poke around there and their respective fora, you might find some stuff that piques your interest
CppCheck is another pretty good one. I've used it on several occasions.
Best bet is to use multiple ones: each one will find a slightly different subset of issues. Also turning on all warnings in your compiler.
I've use Coverity and C-Stat (targeted at embedded market) as commercial products. Coverity does some nice stuff, but it's really pricy.
I wish StackOverflow existed, and notably this curated list of good books.
It is rather unfortunate that there is a lot of C++ tutorials and books out there, that are either sorely outdated or that never were good to start with, despite some glowing recommendations. And as a beginner, it's really hard to spot the difference.
Good news for you, though, C++ Primer being on the list above, I expect it to be one of the few good ones.
You can upgrade the GCC version used by C4droid with this plugin:
https://play.google.com/store/apps/details?id=com.n0n3m4.gcc4droid&hl=en
Then you just have to make sure you're passing the command line option to the compiler to enable C++14 features. ( -std=c++14 )
I'm playing a lot with nana (http://nanapro.org/en-us/) nowadays. It is very lightweight and the API is really nice. It's not so feature complete or battle tested as Qt or WxWidgets but if your needs are simple it is a very good choice.
> seeding off of time(nullptr) isn't in of itself that bad
It's super bad. It has 1-second granularity, and makes identical seeding (across different processes, computers, etc.) especially likely. random_device is a simpler source of a non-deterministic 32-bit integer, and (with a bit more work) it can be used to fill the whole state of an mt19937.
> Everywhere I've seen
Not everywhere. In Rand Considered Harmful I extensively skewered this, plus its more subtle and virulent form, "use floating-point scaling".
> you're still at the mercy of the implementation
I'm full of mercy! I dispense mercy in 10-megaton airbursts.
> I don't recall seeing anywhere a guarantee of quality that any of the random number generators would or should past muster for being cryptographically sound.
The Standard does not guarantee this, but it suggests that random_device should be such an engine. VC guarantees this.
> Even if you utilize OS level entropy generators doesn't make you safe from attack or even a DOS style attack.
That's not what "cryptographically secure pseudorandom number generator" means. What that means is, given any amount of the output, it is infeasible to predict other output.
You have a range of optional<T>
s. You flat-map it and now you have a range of the contents of all of the engaged optionals.
For example, you have a bunch of things you want to try to parse, and you need to continue with the results of all the ones that are parsed successfully.
Edit: This is basically what Kotlin's <code>filterNotNull</code> is. Rather than container semantics, it treats its form of optionals (i.e., nullable types) specially in the library.
The books you listed are all really sub-par and don't teach you well at all. And C++ Primer does in fact tell you exactly why to use things. In fact, it will go into more detail as to why than any other book. And Bjarne's book is actually short. The bulk of the book you do in 2 months I'd say. My first language was C++ and we used Bjarne's book in my course. You will actually waste more time if you skim over key concepts.
>and no, despite what people say, it does not teach you an inordinate amount of C.
Yes. Yes it does. The book uses C style strings, puts them in an array -- a characteristic of C
In C++ Primer Plus introduction, it states even
>C++ Primer Plus discusses the basic C language and presents C++ features,
And I know C++ for Engineers and Scientist - Gary J. Bronson runs the same issues.
Sam's book is too bereft to be useful.
Sticks with Bjarne's book and do a chapter a week. End with PT1. You'll want to learn operator overloading and templates more in depth, + inheritance and polymorphism.
I also found CH17, CH4-6, particularly great.
If you read down the comments on the Hacker News coverage of Warp, you'll find DannyBee demonstrating that Clang's preprocessor is 40% faster than Warp.
Seems like much ado about nothing.
>Then you need early adopters (I mean production-ready projects from more brave teams).
You mean like these? Some of the most well known from that list: Canonical, Wink, Mozilla, Atlassian, npm, DropBox, Chef, and Samsung SmartThings.
And not on that list, but Microsoft just recently announced that they're using Rust in the security-related bits of Azure IoT Edge.
Regarding only needing some specific header-only boost libraries: Have you tried <u>bcp</u>? A little tool shipped with Boost to extract only specific boost libraries including all dependent files.
I've used it with success for our own projects with both compiled and header-only boost libraries. For compiled libraries its a little tricky but Google helped me all the way.
boost::variant
is already implemented as a tagged union, basically the same as a Rust enum. It can be initialized from any of the possible contained data types. For type-safe match
ing, use boost::apply_visitor
. See here for an example of that. The main drawback is that you need to use a separate functor for the match body (so the "match
" arms can't implicitly access the outer scope).
boost::variant
won't always be as efficient as Rust enums (boost::variant
is sometimes forced to heap-allocate, and the underlying representation might be bigger because C++ allows null pointers), but as far as I'm aware, it's more or less as good as it can be with current versions of C++.
How is TheInputHandler::Instance() created? If it's created on the heap and you didn't explicitly initialize the m_mousePosition field, that pointer will contain garbage, and might by chance be pointing to a random spot in memory that it can write to without causing a crash. It won't be initialized with a NULL pointer unless you explicitly ask it to be.
You can detect these sorts of bugs by using Valgrind:
It'll alert you when you try to access memory through a pointer that was never initialized.
Honestly, your best bet would probably be to read a textbook/reference on the language.
Stroustrup's "The C++ Programming Language" is quite good. If you want something more condensed, you could also check out his "A Tour of C++", which is much of the same material in a much smaller package.
If you'll be working with C++11 then I'd recommend "C++ Primer" (not C++ Primer Plus!). That book explains most of the relevant C++11 features throughout the text, unlike some other books which simply have most of the text unchanged and a chapter added to the end about C++11.
It's very large however, so you might have to skim through some of it.
"The Linux Programming Interface " is the standard bible on all things Linux. Other than that, C++ is C++, which means the Effective series (cannot praise these enough) and Primer if you need the absolute basics.
> It is not a database, and it is not an API.
That's where you are wrong. Git, at it's core, is an immutable, distributed key-value database. See also: https://git-scm.com/book/en/v2/Git-Internals-Git-Objects
Also, git is a well established API, there are plumbing commands that you can use. For example, one could use some combination of git ls-remote
, git init --bare
and git fetch --depth=1
to download a snapshot of a specific ref.
I think, there is nothing wrong in using git as a database and as a SCM at the same time, it's practical, easy, and the core concept are, IMO, well designed, especially for this use-case (vcpkg registries).
Honestly, for C++, you'll benefit more from a good book than any online resource. Check out the recommended book list on Stack Overflow.
> backwards compatibility
> Rust makes no such guarantees.
That's actually wrong: https://www.rust-lang.org/en-US/faq.html#why-has-rust-changed-so-much and https://www.rust-lang.org/en-US/faq.html#how-does-rust-language-versioning-work Relevant part: >Now that Rust has reached 1.0, the language is guaranteed to be “stable”; and while it may continue to evolve, code which works on current Rust should continue to work on future releases.
And >Rust’s language versioning follows SemVer, with backwards incompatible changes of stable APIs only allowed in minor versions if those changes fix compiler bugs, patch safety holes, or change dispatch or type inference to require additional annotation.
You'll love C++17 then:
template<auto v> struct integral_constant { static constexpr auto value = v; // [...] };
But boy will you love Boost.Hana.
At that point you would need to use an arbitrary precision math package. GMP is the most commonly used. Boost.Multiprecision is also nice, as you can choose between a slower but header-only backend implementation for convenience, or it can use GMP for maximum performance if you have that built and installed.
Your comparison operator is O(n). That makes insertion O(n log n). That's not good. You might want to have a look at Boost.MultiIndex.
In general, if I was going to skip boost multi-index and roll my own of this type of thing using stl containers, I'd use a vector to store the values and a hash to map keys to vector indices (using form 2 of this. Then you get amortized O(1) insertions while still having the properties of uniqueness (by key) and iteration by insertion order. But really, I'd just use Boost.MultiIndex because the problem has already been solved.
I remember being in the same shoes as you when I was 14. I got interested in C++ after playing Half Life and that's how I became a programmer.
Keep practising and practising. It's like a foreign language where the more practise, the better you get.
I suggest to learn from a book while also building a 2D game with SFML so you can apply what you've learnt. Go to Stack Overflow if you get stuck.
I found the link in the blog post much better than the post itself:
http://clang.llvm.org/docs/Modules.html#problems-with-the-current-model
It at least acknowledges these issues:
> [...] the system headers themselves may require some modification, if they exhibit any anti-patterns that break modules. Such common patterns are described below. > > [...] > > Missing includes - Headers are often missing #include directives for headers that they actually depend on. [...] > > Headers that vend multiple APIs at different times - Some systems have headers that contain a number of different kinds of API definitions, only some of which are made available with a given include. [...] There is no sane way to map this header to a submodule.
Thanks, at least someone noticed the elephant in the room, even if this only happens near the end of the otherwise optimistic and forward-looking text.
I can't comment how it is for Linux folks, but both these things occur in spades with Windows Platform SDK. Until someone does a humongous job of reworking the headers to be amenable to modules, the entire feature on Windows will be just something you do with your own code or maybe with non-platform-specific libraries.
It is my opinion it is the best of a bad bunch; really QT merit is in that fact that wxWidget and GTKmm are worse: see here: http://www.wxwidgets.org/develop/standard.htm
It does somethings well like being well distributed, documented and most importantly has as drag and drop creator.
However the problem with it is it is of a design style not really compatible with modern C++. It doesn't namespace , it defines it's own containers (least forgivably is QString, how I hate you), everything is 'new' manually.
The fact is QT is a C++ library implementation in it's own right, it can be used more or less in place of the standard library, however it is my view that it is worse than std lib because it takes a very esque approach ins't standard.
Finally if I want to have a graphic window I do not want my end users to have get QT network and audio libraries it is just too big.
I suggest starting with C++. Then you will not need to unlearn C when you start learning C++ at a later stage.
C++ Primer Plus book: >Also if you know C, you must unlearn some programming habits as you make the transition to C++
Personally, I think CMake is the least evil of those (but still pretty evil, if you want to do anything it doesn't support out of the box). I also keep an eye on premake for future projects.
I prefer the bare-bone MinGW-w64 distro which is actually used by the Nuwen - but Nuwen is awesome if you want boost and other stuff bundled and ready to go!
> Lambdas allow ad-hoc functions to be declared at block scope (something that was illegal before in C++). The lambda function (functor) is only available within the scope of func() in this example; unlike a function, which would have global scope (or file scope if declared as static).
It can be done in pre-C++11 indirectly by creating a local scoped class definition with static function. Like this for example. It is not pretty, but I have seen this done here and there. The lambda did help clean this up (and allowed for less typing).
What would be nice to have though are polymorphic lambdas.
> attribute
People don't want C++ attributes to alter the program behavior. Metaclass might do the job, but it's still in the early stage. Another choice is to use CRTP (e.g. use boost::totally_ordered
in <boost/operators.hpp>), but it's intrusive, as one needs to modify the class definition.
If you gonna pull boost into your project, Boost.Hana is also worth a look.
struct Cat { BOOST_HANA_DEFINE_STRUCT(Cat, (std::string, name), (int, age), (std::string, furColour) ); };
Cat cat = {"Stimpy", 5, "Red"};
const auto& a = [](const auto& pair) { std::cout << boost::hana::first(pair) << ": " << boost::hana::second(pair) << "\n"; };
boost::hana::for_each(boost::hana::accessors(cat), a);
const auto& b = [](const auto& x) { std::cout << x << "\n"; };
boost::hana::for_each(boost::hana::keys(cat), b); boost::hana::for_each(boost::hana::members(cat), b);
http://www.boost.org/doc/libs/1_46_1/boost/optional/optional.hpp
That's the header for boost optional.
Do I want boost assert, config, and all the other supporting libraries? Generally no. I think boost is a great testbed for new techniques and constructs, but as a dependency, including any of it in isolation is inconvenient at best and untenable at worst.
Have you considered just using a tool like valgrind and fixing leaks, instead of trying for GC?
There's a little inner OCD guy in me that, when using languages that aren't inherently GC'd, likes to make sure stuff doesn't leak in the first place.
There is a very good reason for this.
> A further difference between IDEs and batch compiler is that they often impose very different requirements on the front-end: they depend on high performance in order to provide a "snappy" experience, and thus really want techniques like "incremental compilation", "fuzzy parsing", etc. Finally, IDEs often have very different requirements than code generation, often requiring information that a codegen-only frontend can throw away. Clang is specifically designed and built to capture this information. > http://clang.llvm.org/features.html
... I have youtube also... but really, he says many things that people on here never agree with, oddly it's what C++ ACTUALLY IS and why he kept all the old code like a ship at sea collecting barnacles. He's a great writer, his book complements C++ Primer really well. And I think that he's never going to give up on "fixing" C++, he's a true programmer/computer scientist/realist.
Visual Studio and CLion (which backs off GDB if I remember right) have pretty decent debuggers.
If you can get VS Code to properly detect your environment, it seems to be able to integrate with a few different debugging services. https://code.visualstudio.com/docs/languages/cpp#_debugging
Unfortunately most of the best visual debuggers are part of the IDE itself, rather than a standalone element.
Few days ago I was searching for some lightweight GUI library for a plugin (I am familiar with Qt, WxWidgets, Win32++, MFC, but they are too big or have not quite 'modern' interface) and found Nana library. Didn't use it too much, but from what I've seen it's pretty easy and 'modern' way of implementing a GUI in C++.
Also, unless you need performance improvements for specific use cases, I'd prefer wrapping the class within boost::synchronized_value : http://www.boost.org/doc/libs/1_62_0/doc/html/thread/sds.html
This makes it possible to guarantee unsynchronized access cannot happen by mistake.
The simplest solution:
void print_grid(int* grid, int rows, int columns) { /* ... */ grid[row * columns + column]; }
However this is inflexible and error-prone. You don't want to use arrays unless you have to; it's better to use std::vector instead unless you have a compelling reason not to. So a better (but still simple) solution would be:
void print_grid(vector<vector<int> > grid) {
This is a "jagged" 2D array, i.e. it allows each row to be of a different length which is not what you want for a grid.
Even better but more complicated solution:
void print_grid(boost::multi_array<int, 2> grid) { /* ... */ grid[row][column] }
Boost.MultiArray is a general multi-dimensional array library, but is a slightly more complicated solution than just using a vector of a vector.
This lecture series by /u/stl is probably the best introduction to the STL.
During last week's meeting in Issaquah, some new features requested through National Body comments were merged into the draft Standard. See the latest 3 entries of corresponding the Clang progress table. So depending on whether gcc also incorporated those features, they are the first to be C++17 ready.
Contribute to Clang! Not only will you code be looked at by friendly C++ experts, but you will learn more than enough about C++. And you're helping to make the C++ world a better place.
Not just for C++, but I have really been liking devdocs.io. For C++, it's the cppreference documentation, but if you're also using other languages, it's handy to have it all in one place.
Bonus points if you use duckduckgo: !dd <search term>
.
PVS-Studio did UEEngine as another of their interesting marketing pieces around their static analysis toolchain:
https://www.unrealengine.com/blog/how-pvs-studio-team-improved-unreal-engines-code http://www.viva64.com/en/b/0249/
If you simply must learn MFC, the best books remain the two editions of Jeff Prosise's book on the subject.
The first edition is better, in my opinion. It's available for less than a dollar on Amazon US ( https://www.amazon.com/Programming-Windows-MFC-Microsoft-Foundation/dp/1556159021 ).
It's not "up to date" in that it wasn't written recently and doesn't cover the last two decades' worth of additions to the MFC libraries. It is "up to date" in that it explains slowly and carefully the thinking behind MFC, and how to actually write for it yourself (i.e. not just pushing buttons on a wizard). If you learn form this book, you'll know what you're doing and you can then just browse through the current MFC API to see what additions have been made available to you. Also, by learning from Jeff Prosise, you'll actually have a better understand of MFC than the vast majority of people writing code in it, and you'll be horrified at how ugly and wasteful the wizard generated code is compared to what you can bang out yourself. People with many years' of MFC wizard experience will stand in slack-jawed awe as you craft tight MFC code with the power of your own mind.
Think carefully about why you want to learn it, though. The good reason for learning it would be that you've got to maintain a set of code that use it. If you're looking to get started with GUI programming, it's a bad choice.
Don't do #2. There are a lot of differences between C and C++, and good C++ code usually means avoiding C features.
For the sake of doing well in your classes, it sounds like you should focus on C++ for at least a short time, then later you can transition back to Java.
There are a lot of ways to write bad C++, so be highly selective about who you learn from. I recommend learning directly from the guy who created C++, Bjarne Stroustrup. He has several books that you can progress through nicely. "A Tour of C++" is a thin book that can serve as an intro. "Programming: Principles and Practice Using C++" is a thicker and more detailed book that's still meant for newer programmers. And finally "The C++ Programming Language" is a highly comprehensive book meant for advanced programmers.
For beginners, I would recommend Programming Principles with C++ by Bjarne Stroustrup. It is a very well written book in the sense that it holds your hand along the way while learnin the language and develops concepts gradually. I really like it. However, if you have considerable experience with other languages, it might come a little "slow" to you. In that case, C++ Primer is the best. Also you would really like to look into this link because it is "the" link for C++ book recommendations.
http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list
Long story short; <cstdint> guarantees the types in std namespace and <stdint.h> guarantees the types in global namespace. Thus: if you want to be sure your code compiles everywhere always use std:: with cstdint.
Though it has bothered me as well; just in case you didn't know you can make a preprocessor define of NOMINMAX
and it won't define min/max. You would need to do that for pretty much for every project in your solution. It isn't perfect as GDIPlus won't compile without those macros defined, as an example. Here is a screenshot from windows.h: https://www.screencast.com/t/C3TG5ugN88l showing this preprocessor define as well as some others. Hope that helps!
#pragma once
prevents you from including the same header in the same source file multiple times, it does nothing to avoid this problem. You're probably just aware enough not to define a variable in a header.
Free when your business conditions meet the license terms,
https://visualstudio.microsoft.com/license-terms/mlt031819/
When working in countries where companies take audits seriously, it matters which version you have installed, the consequences will be way above paying 1199.99.
No comment on the code, but the layout of your site is kind of breaking on my laptop: image. Chrome 47.0.2526.106, on arch linux. I can only see about 40 characters per line of the code without scrolling.
Also, small note, https for your domain returns a cert with CN for "*.inmotionhosting.com" and then 404s. I assume this is an artifact of your host, but if you are unaware, ssl certs are now free via Let's Encrypt. I realize you aren't really transporting anything necessarily requiring encryption, but if it's free, why not, right?
Edit:
Ok, I've gotten this to compile on clang 3.7.0. But I had to change uint32 -> uint32_t. I'm not sure where 'uint32' is supposed to be defined. The type from "cstdint" (which isn't included) is uint32_t.
boost::containers::flat_set
boost::containers::flat_map
boost::containers::static_vector
boost::containers::small_vector
default_init_t
overloads for all vectors types in Boost.Container to allow default-initialization of elements when constructing or resizing rather than always value-initializatingNot in Boost, but also noteworthy is Howard Hinnant's <code>short_alloc</code> allocator, which can make allocation overhead and locality issues of any container completely moot.
First, before you write your own library, check out what is available in the C++ standard library and boost (www.boost.org). It looks like you are doing stuff with probability so check out http://www.boost.org/doc/libs/1_60_0/libs/math/doc/html/dist.html to make sure it is not already done.
Use templates. The Concepts that people are talking about is based on templates.
If you are using templates a lot, why not just use a .h (or .hpp) header file. Header only libraries are actually the easiest for other people to use. If you just have a single .cpp file, I personally would not bother to try to make a library and instead just tell the user to incorporate probability.cpp into your build. Pugixml (http://pugixml.org/docs/quickstart.html) does this.
For small libraries, I prefer header-only and if not possible statically linked. Especially, if you are doing a lot of math, the header-only may provide some performance improvement as the compiler can better inline stuff.
Herb Sutter in a recent video lecture ("One C++", 16 minutes in) pointed out that the documents that specify the core language for C++, C#, and Java are practically the exact same size. The difference is that the latter two have much larger libraries defined in the standard.
Now, of course, maybe that just means the C++ document is much more concisely written. I can't really believe that core Java is bigger than core C++, but it's an interesting little datum nonetheless.
Most of the developers that write these kinds of tools are only really interested in modern C++. There are quite a few tools that do the exact opposite of what you want (i.e. detect that something like your second example could be a ranged for and modernize it) despite that being more difficult and requiring heuristics.
Translating auto and ranged for shouldn't be too difficult. Trying to convert variadic templates sounds like a can of worms, but it may be possible if the resultant source code is intended only for compilation and not for editing (though beware of the way forwarding will break down without rvalue references).
The best way to implement this would probably be as a clang tool. clang's LibTooling is probably the most appropriate approach. clang will give you an AST representing the input program and you can make your adjustments when outputting this back into C++. Ranged for statements are actually already transformed into normal for statements using the equivalency provided in the standard. Auto would be handled by removing AutoType sugar from a declaration's type.
I have seen Java ports of older C++ code be faster.
But when the two languages are coded side by side, Java is still on the order 1.5-2.0x the performance of the C++ code in most normal general purpose programming situations.
Much of this comes not from GC or the JIT being slow, but from more objects being allocated on the heap or inside of object wrappers, when they would have been native, stack-born elements in a C++ program.
Especially arrays and collections -- C++ has a strong advantage here as they can keep the memory contiguous and keep the code/data they need in the CPU caches easier.
They are working on value types for java which will include making memory contiguous collections/arrays possible. It will be a nightmare for the c++ guys, as Java is going to get a fuck of a lot faster when that happens. (http://openjdk.java.net/projects/valhalla/ for details)
> For sure I will use an ide, but the way Microsoft describes cpp development in Windows suggests that vs is neccesary.
It is not, it's just a very convenient way and VS is simply the best IDE on Windows so there's not really a reason to not use it. But the compiler can be used on its own and you can also generate VS build files from CMake (or Meson). In general you always use something cross platform like CMake to describe your project and then generate the actual build files (VS, make, ninja, whatever) from that. Here is the site on VS CMake integration.
If you really don't want to use VS then just get the build tools from https://visualstudio.microsoft.com/downloads/#build-tools-for-visual-studio-2019 . You can then use the "x64 native tools command prompt", cd to your directory and do your usual workflow, for example with CMake
cd yourprojectpath mkdir build cd build cmake .. cmake --build .
and do the editing in the editor of your choice.
Lot of "old" books are interesting to read, like "Effective"s, or "C++ in Depth" series (red books). The question is rather: what order to read them?
It's probably better to start with more recent books, like C++ Primer (Lippmann), C++ STL (Josuttis), C++ Langage (Stroustrup), etc. And Modern Effective C++ for C++11/14 (Meyers) (a must-to-read for me).
Don't buy any book from Scott Meyers or Herb Sutter if you're just gonna buy one book. All of their c++ books are worth reading but not a good starting point for learning c++. They are aimed at programmers who know at least the basics of the language and want to avoid pitfalls and learn guidelines to write better code. After you read for example the "A Tour of C++" they're a good resource.
"The C++ Programming Language" is a reasonable alternative if you wanna jump in the deep end.
edit: s/Meyer/Meyers/
Woah, woah. LGPL is not "free for commercial usage". It requires you to allow the user to use your app with a different version of the LGPL code. You can't statically link to Qt, you have to use dynamic linking and allow the user to use a different shared library.
Now, tell me, how do you do that on iOS or Android when the app is signed and sealed? There is Ministro on Android, enabling shared libraries. but try telling your user "ThisApp requires additional libraries, download from Google Play" and a lot of them will uninstall right away. I don't even know how could you do it on iOS, never used it.
Anyway, what I'm saying is that it's not so straightforward to use LGPL on mobile.
> What's the new stable to use? Sorry, I really don't know.
Buster was released less than a month back, it has GCC 8.3.
> Edit: is it Stretch? It's still on gcc4 isn't? https://packages.debian.org/stretch/gcc
The page you linked shows GCC 6.3. Note that the 4:
at the front is the epoch, typically used if upstream changes their versioning system.
I rock Debian Unstable, so don't have to worry about old compilers and stuff fortunately.
Doesn't Qt fit those criteria?
You can use Qt under the LGPL, which allows you to keep your application proprietary. You just have to provide a means to the user to link your application to another version of Qt, which can be done by simply dynamically linking to Qt.
> I just did not want to use boost
as an external dependency
I think the fact that people just say this without qualification reveals a lot of the things that are wrong with the C++ community at large.
Why would you not want to depend on a widely-supported, heavily peer reviewed library, which is mostly header-only, and which has been the basis/testing ground for so much of the standard library, and instead roll your own?
Do you think you can write code for your one-of project that's of higher quality, better tested/reviewed, et cetera than the code in Boost?
If you said that you were writing the library as a hobby project and just wanted to see how something like a reactor/proactor was implemented (which you clearly wouldn't get to do just consuming one) that'd be one thing, but your comment indicates that you actually built this software for actual use somewhere. Why then would you forego an already built, heavily reviewed and tested, and widely praised piece of software (Boost.Asio) in favor of creating your own?
If you want to use futures Boost.Asio can do that out of the box with no glue code.
If you like the reactor model better than the proactor model it's easy enough to write some code on top of Asio that makes it behave like a reactor.
One nitpick with the Boost.DLL example:
my_plugin::name() return a std::string. Unless your toolchain is using the same compiler and runtime, you really don't want to return a std::string. Otherwise, you run the risk of your dll using a different implementation of std::string that what the client code uses. Additionally, you're allocating the string memory in the dll and freeing it in client code. In the case of Windows, this can blow up if you're using two different CRTs.
I realize that they address this in the "missuses" section, but there should really be a disclaimer with this example.
EDIT: I'm specifically referring to the example in http://www.boost.org/doc/libs/1_61_0/doc/html/boost_dll/tutorial.html
coroutines let them chain naturally: http://www.boost.org/doc/libs/1_60_0/doc/html/boost_asio/overview/core/spawn.html and http://www.boost.org/doc/libs/1_60_0/doc/html/boost_asio/overview/core/coroutine.html
(coming to standard C++, too)
Cinder is the fashionable graphics library in C++ right now. Its main advantage is that its modern C++ as opposed to all those old C-style API's.
Edit: I used SDL, Allegro, DirectDraw, Direct3D/OpenGL directly, imagemagick, etc. But would choose Cinder next time.
Qt Creator also uses LibClang
, because of the promise of a stable interface.
LibTooling
is the C++ library that should be used.
The fine manual has the gory details.
Thanks for pointing out the resources and for designing CMake and writing the documentation. But speaking as someone who wanted to learn Modern CMake I found it difficult to find the material.
If you go to http://isocpp.org you see Get Started which points to stuff like A Tour of C++ or Elements of Modern C++ style. In fact, you would have to be a C++ programmer living under a rock, not to at least have heard about C++11/14 and all the benefits it brings.
When I go to CMake.org and go to documentation I see Training Materials including a CMake Tutorial. Clicking on the Tutorial, I am instructed about cmake_minimum_required 2.6. There is no good starting point that leads a beginner towards Modern CMake. I actually did not see your nice overview at http://www.cmake.org/cmake/help/v3.4/manual/cmake-buildsystem.7.html because it was in the Reference Manual section of the documentation, and I was looking more for a tutorial or overview.
Up until a few months ago, I really did not know about modern CMake, and learned about it from a fellow programmer. When I asked him if he knew a good overview of Modern CMake, he said he did not and had picked up most of his knowledge over time from bits and pieces of stack overflow answers.
I think Modern CMake is the perfect complement to Modern C++. However, as is evident just in this discussion, there are a lot of people in C++ who despise CMake because all they know is the old style CMake, and when they are exposed to Modern CMake are pleasantly surprised (see the reply of u/sazzer to u/doom_Oo7 for an example from this discussion).
Thanks again for making CMake a whole lot better.
If you're wanting to learn C++ specifically for game development, you might be better of killing two birds with one stone and reading a book like Game Programming Patterns