Hot answers tagged

230

Coding style is ultimately subjective, and it is highly unlikely that substantial performance benefits will come from it. But here's what I would say that you gain from liberal use of uniform initialization: Minimizes Redundant Typenames Consider the following: vec3 GetValue() { return vec3(x, y, z); } Why do I need to type vec3 twice? Is there a point ...


184

C was never a subset of C++. The most obvious example of this is int new;. This has been true since C89 and C++98, and the languages have only grown further from each other as new standards have come out. Should I stop using the term C/C++ Yes If the answer to #1 is yes, how would I call a program that use a mix of C and C++? A source file is ...


112

It's a case-by-case situation. It sometimes makes code harder to understand, sometimes not. Take, for instance: void foo(const std::map<int, std::string>& x) { for ( auto it = x.begin() ; it != x.end() ; it++ ) { //.... } } is definitely easy to understand and definitely easier to write than the actual iterator declaration. I'...


108

There has to be a reason why these terms come together so often. While you should not tell your C teacher that his language is a subset of C++, there is some truth here. Others already have exposed your teacher's point of view. This is very nice (and illustrated with examples, etc.). But we don't live in an ivory tower, or a book. Your big boss could not ...


98

Short answer: More completely, my current opinion on auto is that you should use auto by default unless you explicitly want a conversion. (Slightly more precisely, "... unless you want to explicitly commit to a type, which nearly always is because you want a conversion.") Longer answer and rationale: Write an explicit type (rather than auto) only when you ...


94

Look at it another way. Do you write: std::cout << (foo() + bar()) << "\n"; or: // it is important to know the types of these values int f = foo(); size_t b = bar(); size_t total = f + b; std::cout << total << "\n"; Sometimes it doesn't help to spell the type out explicitly. The decision whether you need to mention the type isn'...


85

It's simple. C++11 makes code dramatically easier, cleaner to write, and faster. nullptr is a VAST improvement over the old 0. It's type-safe and doesn't convert when it shouldn't- unlike 0. It's a good thing that nullptr won't convert to an int. It doesn't make sense for that to happen at all. Do you know what the C++ Committee found when they tried to ...


63

I'm going to disagree with Nicol Bolas' answer's section Minimizes Redundant Typenames. Because code is written once and read multiple times, we should be trying to minimize the amount of time it takes to read and understand code, not the amount of time it takes to write code. Trying to merely minimize typing is trying to optimize the wrong thing. See the ...


56

If you can avoid shared ownership then your application will be simpler and easier to understand and hence less susceptible to bugs introduced during maintenance. Complex or unclear ownership models tend to lead to difficult to follow couplings of different parts of the application through shared state that may not be easily trackable. Given this, it is ...


50

First, some rules of thumb: Use std::unique_ptr as a no-overhead smart pointer. You shouldn’t need to bother with raw pointers all that often. std::shared_ptr is likewise unnecessary in most cases. A desire for shared ownership often betrays a lack of thought about ownership in the first place. Use std::array for static-length arrays and std::vector for ...


48

First, I'll note that although I only mention "C" here, the same really applies about equally to C++ as well. The comment mentioning Godel was partly (but only partly) on point. When you get down to it, undefined behavior in the C standards is largely just pointing out the boundary between what the standard attempts to define, and what it doesn't. Godel'...


48

The world that Bjarne lives in is very... academic, for want of a better term. If your code can be designed and structured such that objects have very deliberate relational hierarchies, such that ownership relationships are rigid and unyielding, code flows in one direction (from high-level to low-level), and objects only talk to those lower in the hierarchy, ...


44

"Premature optimisation" is not about using optimisations early. It is about optimising before the problem is understood, before the runtime is understood, and often making code less readable and less maintainable for dubious results. Using "const&" instead of passing an object by value is a well-understood optimisation, with well-understood effects on ...


43

Going against the flow I would say it depends on the context. The term "C/C++" is usually not appropriate when saying something like "this is a C/C++ program", but this has been explored to depth in other answers. However, there might be contexts where C/C++ can be appropriate. There are various libraries which usually have both a C and a C++ API. I guess ...


40

I was mistaken, there is a set of "Xtos" functions, they are all just named to_string. Each to_string is overloaded to take a different basic type, i.e.: std::string to_string(float f); std::string to_string(int f); ... See here for more info.


38

I don't believe I've ever used std::shared_ptr. Most of the time, an object is associated with some collection, to which it belongs for its entire lifetime. In which case you can just use whatever_collection<o_type> or whatever_collection<std::unique_ptr<o_type>>, that collection being a member of an object or an automatic variable. Of ...


38

There are a lot of usability enhancements that make C++11 more comprehensible to a beginner, especially one who has experience in other languages with those features. Other changes in C++11 are only of interest to advanced users, so you're likely to get overwhelmed if you pick up a book that is designed to mostly teach the differences. Make sure any book ...


38

These are phantom type parameters, that is, parameters of a parameterised type that are used not for their representation, but to separate different “spaces” of types with the same representation. And speaking of spaces, that’s a useful application of phantom types: template<typename Space> struct Point { double x, y; }; struct WorldSpace; struct ...


37

The motivations in C++ are more extreme, as types can become vastly more convoluted and complex than C# types due to metaprogramming and other things. auto is faster to write and read and more flexible/maintainable than an explicit type. I mean, do you want to start typing boost::multi_map<NodeType, indexed_by<ordered_unique<identity<NodeType>...


37

Almost every word you might think of adding as a keyword to a language has almost certainly been used as a variable name or some other part of working code. This code would be broken if you made that word a keyword. The incredibly lucky thing about auto is that it already was a keyword, so people didn't have variables with that name, but nobody used it, ...


30

The simplest way is to provide the operator overloads yourself. I am thinking of creating a macro to expand the basic overloads per type. #include <type_traits> enum class SBJFrameDrag { None = 0x00, Top = 0x01, Left = 0x02, Bottom = 0x04, Right = 0x08, }; inline SBJFrameDrag operator | (SBJFrameDrag lhs, SBJFrameDrag rhs) { ...


30

In general the SO users ask the person who is asking the question to choose a language: C or C++. Why? There are many subtle differences between C and C++. For example, in C++, a const variable at global scope has internal linkage unless declared extern, but in C it has external linkage unless declared static. By saying "C/C++", the OP is asserting ...


29

C++11 is not a new language; it is only an extension/modification of C++ that you already know . C++11 just like any other programming language consists of features. A lot of them were there from before, some of them are new. But your question really is, should I learn all features of the language (in this case C++11), or only familiarize myself with 90% ...


29

GCC's popularity and usability is not questionable. GCC is still great compiler and most widely used. GCC supports languages that clang does not aim to, such as Java, Ada, FORTRAN, etc. GCC supports more targets than LLVM. GCC is supporting C++11 From https://stackoverflow.com/questions/12210102/does-gcc-4-7-1-support-threads mingw build at http://...


28

In your example: for(auto it = x.begin(); it != x.end(); i++) { it->?? } there has to be a declaration for x visible. Therefore the type of it should be obvious. If the type of x isn't obvious, then the method is too long, or the class is too large.


27

IMO, you're looking at this pretty much in reverse. It's not a matter of auto leading to code that's unreadable or even less readable. It's a matter of (hoping that) having an explicit type for the return value will make up for the fact that it's (apparently) not clear what type would be returned by some particular function. At least in my opinion, if you ...


24

You should learn it if you think you will need to know it in the future in order to get a job. If you are confident you will remain marketable in the workforce as a C/C++ [ and whatever else you might know ] then don't learn it. If your boss tells you to use C++11, say "no, I don't do that". If he fires you, go work somewhere else. Learn C++11 when you ...


24

No, you should not feel uncomfortable using auto. Just use it in situations where the type is obvious, or where no one is going to care about it A classic example (IMO) of where auto is handy: std::vector<sometype> vec ... ... //some code ... ... for(auto iter = vec.begin(); iter != vec.end(); ++iter) { //something here } Nobody really cares ...


23

I understood that GCC is falling out of favour because the people maintaining it have become somewhat arrogant, and now that LLVM is here (and is very good) people are voting with the feet. Slashdot had a discussion about LLVM's new support for C++11. _merlin says: Oh I don't think anyone thinks it's evil, just that it's pure self-interest rather than ...


22

An alternative to friend (well, in a sense) that I use frequently is a pattern that I've come to know as access_by. It's pretty simple: class A { void priv_method(){}; public: template <class T> struct access_by; template <class T> friend struct access_by; } Now, suppose class B is involved in testing A. You can write this: template <...


Only top voted, non community-wiki answers of a minimum length are eligible