background preloader

C++

Facebook Twitter

Metaprogramming

Boost. C++0x. 0x. Networking. XPCOM Part 1: An introduction to XPCOM. The C++ bashing season is back. It seems there is a lot of dislike and hate for C++ out there. This isn’t new – it has always been like this. But lately this issue comes more into focus in the programming community, and I don’t even understand why. After all, C++ is certainly a less important language now than it has been a few years ago, since more applications are being written in dynamic languages like Python, and new languages like C# gained some popularity and market share on the expense of C++. Proggit fame Proggit, the programming section of reddit.com is probably the most popular place for general programming discussion these days. Traditionally, Proggit was considered by many to be a snub place where language zealots reside and advice everyone to learn Haskell and Lisp. Here’s a short collection of recent discussions, with the original articles that started them: A redditor asked two months ago whether he’s crazy for liking C++.

You like C++ because you’re only using 20% of it. So why is C++ so bad? Making a C codebase reentrant by turning it into a big C++ objec. Published Sep 21 2009 by Phil Dawes Over the last couple of months I've been spending my spare time working at making the factor vm codebase reentrant. The Factor vm is a mostly C codebase with global variables holding the runtime state, and I wanted to be able to run multiple vms in a single process. I thought I'd document the approach I used to make the C portions reentrant because it's one of those things that's obvious and easy in hindsight but took me a few abortive attempts and some wasted time to find the best way. The output of this process is one big vm object with all the global variables and functions in it. I originally spent some time trying to refactor the vm codebase into an OO model but this turned out to be a really subjective operation and I ended up thinking I'd do more harm than good attempting that.

Ultimately I opted for the one-big-vm-object approach, with the previso that it can then be refactored into an object model later if that's deemed a good idea. The SNIPPETS archives project. Compiling Templates. I Didn’t Order That, So Why Is It On My Bill, Episode 1. I Didn't Order That, So Why Is It On My Bill, Episode 1 June 22nd, 2009 C++ was designed to ensure you "only pay for what you use," and at that it is mostly successful. But it's not entirely successful, and I thought it might be interesting to explore some counterexamples: C++ features you don't use but still negatively impact performance, and ways in which other languages avoid those issues. So here's the first episode of I Didn't Order That, So Why Is It On My Bill, to be continued until I can't think of any more.

Inline Functions The C++ standard says this: A static local variable in an extern inline function always refers to the same object. In other words, static variables in inline functions work just like static variables in any function. But wait, it also says this: An inline function with external linkage shall have the same address in all translation units. That's borderline silly.

So hopefully I've established that you don't use this feature. And it gets a little worse. What I currently hate most about C++ Everyone knows that global variables are bad and should be avoided wherever possible. Why? Because each global variable is, in effect, an implicit argument to every function that can see the global variable.

The same thing is true of any non-local state. And the presence of non-local state means that you can’t reason locally about your code. That makes your code more complex, and complex code is likely to have more defects. And the thing I hate about C++ (and other object-oriented languages) is that it vigorously encourages non-local state. Non-local state within classes First, of all, C++ encourages (nay, forces) non-local state within classes, because all class methods have access to all fields within a class, even the ones they don’t need to. But problems appear when classes grow larger, when they start to look like what would be a whole module in a non-OO language like C. Let’s consider a single field, _thisfrag, which holds a fragment of LIR code.

Non-local state beyond classes. C and C++ are not the same language. In the web world, a world I’ve made my way back to in the last year, pointers are an exotic relic of the past. Seriously. I never got the memo; there was no going away party, I was just sitting there, minding my own structs and boom, next thing I know, I was that guy that hadn’t realized that . But there is a certain reverence for the old ways. You’re supposed to learn C or C++ (often just written as “C / C++”) to be a well rounded dork, much like you’re supposed to have read Shakespeare.

This is all fine and well, and I agree. But there’s one sticking point. All of these are true in both languages. However, . Modern C++ is usually written in an object-oriented style. It’s beyond the scope of this entry to get into the many differences between the two, but I decided to implement a common pattern in programming, the in C, C++ and Java to illustrate the differences. Observer Pattern in C: Observer Pattern in C++: Observer Pattern in Java: class FooListener implements Foomatic. Of course. 10 reasons you should know C++ The Positive Legacy of C++ and Java. Computing ThoughtsThe Positive Legacy of C++ and Javaby Bruce EckelMarch 14, 2009 Summary In a recent discussion, there were assertions that C++ was a poorly-designed language. I was on the C++ Standards Committee for 8 years, and saw the decisions take place. I think it's helpful to understand the language choices for both C++ and Java in order to see the bigger perspective. That said, I hardly ever use C++ anymore.

When I do, it's either examining legacy code, or to write performance-critical sections, typically as small as possible to be called from other code (my preferred approach is to quickly write an app in Python, then profile it and if necessary improve performance by calling small portions of C++ using Python's ctypes library). Because I was on the C++ Standards Committee, I saw these decisions being made.

It also fooled the Java designers who didn't understand C++ well enough. There are plenty of other examples. The list goes on to the point where it's just tedious. Jrm-code-project - Google Code - A random walk through code. C++ and the linker. Copton.net 2.4263102175e-12 C++ and the linker Main Quite some time ago I found a brillant and extensive article about linkers from Ian Lance Taylor. (see the appendix for a list of links to all 20 parts.) Basics For those who don't know what a linker does, and who don't have time to read the 20 articles from Ian, I will give a brief introduction on the topic.

How the Linker Works Ian says that the demand for interoperability with FORTRAN and COBOL was the reason for introducing linkers. A C program need not all be translated at the same time. The term "linkage" is defined in section 6.2.2/2: In the set of translation units and libraries that constitutes an entire program, each declaration of a particular identifier with external linkage denotes the same object or function. So the linkage controls, which equally named identifiers denote the same entity. Each identifier with external linkage must be defined exactly once in the entire program, as defined in section 6.9/5: [...] Know Your Tools. Why C++ doesn't suck (idea) C++ and functional programming idioms. If you’re curious like me, you probably ventured at least once in the scary and mind-bending world of functional programming, came back and told yourself: “It would be nice if I could do this or that in c++”.

FP languages have been present for decades but only recently, we’ve been starting to see the adoption of some of their techniques in classical imperative languages… like higher order functions, closures/lambdas functions, currying and lazy evaluation. For example, Javascript supports closures since version 1.7 and C# from 3.0. Seeing how useful these techniques are, it’s normal to want them in our favorite programming language. We’re already doing a bit a FP without knowing thanks to the standard library algorithms.

To demonstrate my point, let’s take a small program that takes a string as input and return the most frequent character. So far so good, it works and does the job. Hmm… Okay… Let’s see, our “most_frequent_letter” function is now using the standard library algorithms. Volatile - a few notes on its usefulness. There have been a few threads on the MSDN Forums lately, asking various questions more or less related to the volatile keyword, and its usefulness in threads. I've only briefly commented on it earlier in this blog, so I suppose today is as good a time as any to clarify a bit. Historically speaking, the volatile keyword was meant to assure that memory possibly updated by other hardware would be re-read by the compiler on all accesses.

In its search for ways to speed up (or even shrink) the code, the compiler could apply e.g. register assignment or dead assignment optimizations. The former would cause variable values to be cached in registers, and thus not re-read from memory at each use. X = *ptr; // get value at [ptr] y = *ptr; // also get value at [ptr] => may not be the same as the value we read for x to be optimized to x = *ptr; y = x; This may be applied when the compiler can prove that the value at [ptr] isn't being updated by the application.

Overview: C++ Gets an Overhaul. En years after the ratification of the first ISO C++ standard, C++ is heading for no less than a revolution. C++0x, the new C++ standard due in 2009, brings a new spirit and new flesh into the software development world. Brace yourself for state-of-the-art design idioms, even better performance, and a plethora of new features such as multithreading, concepts, hash table, rvalue references, smarter smart pointers, and new algorithms. No doubt you'll find a lot to like in C++0x! New Core Features The two most important features of C++0x are concepts and concurrency support. Concepts enable programmers to specify constraints on template parameters, thus making generic programming and design immensely simpler and more reliable (see Douglas Gregor's excellent introduction to concepts).

Rvalue references are yet another silent revolution. Auto func(int x)->double {return pow(x);} Lambda expressions and closures are another prominent feature of C++0x. Introduction to Programming and C++ C++ Dependency Injection, Part Deux. Last time I talked about a concept called Dependency Injection from the Java world, and compared it to Policy Based Design from the C++ world. The techniques that Java designers have used Dependency Injection for very easily ‘port’ to the Policy Based Design world – and one of these techniques, used in testing, is the idea of a mock framework. Mock frameworks are objects that ‘look, taste and smell’ like normal objects, but are used for purely testing purposes only and are useful in that the user can very closely control their state. This time I’d like to go more into depth on a possible way to utilize Generic Dependency Injection, otherwise known as Policy Based Design, to build a mock object framework. I hope to show you that there are a few, for lack of a better term, ‘hacks’ that work very well for testing.

(On that note, I recall reading a post motivated by Test Driven Development and the creation of Mock Object frameworks, and the question of how to test private state. …run test… Lisp Plus Plus. Welcome to the home of William Paul Vrotney's Lpp! Download Lpp Lpp 1.21.2 is now available for download. Lpp 1.21 is now available for download. Lpp 1.19 is now available for download. Please see the copyright under which this software is covered. Lpp Documentation Lpp documentation is available in HTML and PDF. About Lpp Lpp (Lisp Plus Plus), is a library of Lisp like functions and macros usable in C++ programs. Porting Lisp programs to and from C++. One of Lisp's advertised benefits is that of dynamically typed objects. Lpp strives to provide the full power of Lisp in terms of dynamic typing. All Lpp objects as in Lisp have the same base type.

Lpp provides a the macro for descending into specific Lpp objects. Lpp also provides other useful Lisp objects such as Cons cells, lists, symbols, strings, characters and numbers. Lpp chose address 0 as nil. Symbols are introduced into C++ programs easily with the S() macro. Feedback Please direct comments on the Lpp software to William Paul Vrotney. Dependency Injection in C++ My apologies on the double post – I accidentally clicked “create new page” :0) A really valuable technique birthed in the Java world is the idea of dependency injection. That is, instead of a class having to create it’s own object: class Foo { public Foo(){ bar = new Bar(); private Bar bar; (forgive my Java, it’s been awhile.)

You pass in the object in its constructor, like this: public Foo(Bar newBar) { bar = newBar; } Of course, then, someone else has to be responsible for creating the bar object, so really, you end up just passing in object factories, or having a factory do all your setup for you. (The passing in of object factories case): interface BarFactory { public Bar BuildBar(); class NormalBarFactor implements BarFactory { public Bar BuildBar() { return new Bar(); } class TestBarFactory implements BarFactory { public TestBar BuildBar() { return new TestBar(); } //where TestBar inherits from Bar… public Foo(BarFactory barFactory) { bar = barFactory.BuildBar() } class FooBuilder{ public: private: Protocol Buffers. C++ Style Guide. Definition: Streams are a replacement for printf() and scanf().

Pros: With streams, you do not need to know the type of the object you are printing. You do not have problems with format strings not matching the argument list. (Though with gcc, you do not have that problem with printf either.) Streams have automatic constructors and destructors that open and close the relevant files. Cons: Streams make it difficult to do functionality like pread(). Some formatting (particularly the common format string idiom %. *s) is difficult if not impossible to do efficiently using streams without using printf-like hacks. Decision: Do not use streams, except where required by a logging interface. There are various pros and cons to using streams, but in this case, as in many other cases, consistency trumps the debate. Extended Discussion There has been debate on this issue, so this explains the reasoning in greater depth.

Cout << this; // Prints the address cout << *this; // Prints the contents. The A-Z of Programming Languages: C++ Computerworld is undertaking a series of investigations into the most widely-used programming languages. Previously we have spoken to Alfred v. Aho of AWK fame, S. Tucker Taft on the Ada 1995 and 2005 revisions, Microsoft about its server-side script engine ASP, Chet Ramey about his experience maintaining Bash, and Charles H. Moore about the design and development of Forth. In this interview, we chat to Bjarne Stroustrup of C++ fame about the design and development of C++, garbage collection and the role of facial hair in successful programming languages.

What prompted the development of C++? I needed a tool for designing and implementing a distributed version of the Unix kernel. You can find more detailed information about the design and evolution of C++ in my HOPL (History of Programming Languages) papers, which you can find on my home pages, and in my book "The Design and Evolution of C++". Was there a particular problem you were trying to solve? Where does the name C++ come from? C++ techniques: part 1: curiously recurring template pattern. Reason #947 why C++ is dangerous - and certainly not type-safe.

Beyond C++ C++ Frequently Questioned Answers. C++ Reference. C volatile.