New answers tagged

1

Well, you wanted a compile-time test for checking whether the compiler figures that a function will be called with a nullpointer. Let's take GCC or clang, and it's easy using their builtins: if(__builtin_constant_p(!p) && !p) return (void)std::declval<int>(); This will result in importing a symbol which is never defined if the compiler ...


0

It wouldn't be done at compile time, but it would be fairly easy to define a string type that handled this more gracefully than (at least most implementations of) std::string currently does. The basis would be the fact that NULL has type int and nullptr has type nullptr_t. As such, it would be fairly easy to overload on these types, and have them fail "fast ...


1

Use the strongest guarantee that you are willing to maintain for the foreseeable future. Method 4 (template / static assert) assures that the invariant is always true in a compiled program. However, this implies that the input must be known at compile time, which is not always possible. Method 2 (assertion) and 3 (exception) can fail at run time, so they ...


3

If you have multiple types of Signals that have to be updated in different ways, then the cleanest solution is to create a sub-class for each type of Signal, where the sub-classes only implement the different update behaviours. The proposal for storing a function pointer in the Signal class is just emulating manually what the compiler does for you when you ...


-6

The compiler will optimize both '++i;' and 'i++;' into same set of instructions. Unless, there is any difference in their working. for example 'x = ++i;' and 'x = i++;' will yield different set of instruction. For performance, if it is plain '++i;' and 'i++;', there should not be any different, unless the compiler is so dumb.


-2

Apart from the complete Knuth quote about optimization: We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%. there is also the issue of Readability Doug Crockford points out that both pre-, and postincrement make code ...


6

No, you should definetely not abandom namespaces! Instead, you should organize your code better, and maybe check your architecture again. First, you should not use using namespace MyLibrary::MyModule1; or using MyLibrary::MyModule1::MyClass1; in a header, to avoid namespace polution, since there is no way to undo that (see this question and answers). ...


1

First of all, a std::basic_streambuf is basically the building block of a std::XYZstream. Using one or the other is not choosing between two implementations, it is a choice between a basic building block and a more advanced stream interface that people expect. Use a stream. Based on your comments, it appears that you may be getting hung up on the idea of ...


-1

UNIX has a command called rot13. Not sure if it stands for "rotate" or "this is a rotten cypher". :-). I bet you can find the source code, and its written in C.


0

Crashing gracefully is a good thing most of the time -- but there are trade-offs. Sometimes it's a good thing to crash. I should mention that I'm mostly thinking about debugging in the very large. For a simple program -- although this might still be useful, it's nowhere near as helpful as it is with a very complex program (or several complex programs ...


2

Non-virtual functions are called based on the type that the compiler sees. If you have a Base* variable, then calling non-virtual functions will call the Base functions. That's the difference between virtual and non-virtual; calling a virtual function always calls the function that is appropriate for the object. And you are not assigning an object. You are ...


2

Visual Studio solutions work differently for C++ (compared to C# or VB). With C++ project you do not get "hand held" with your folder layout in the project mirroring that on disk. Instead, with C++ you can put your files anywhere you like, and organise them as you like using filters. eg you can have many folders on disk with lots of C++ or resource files in ...


20

I have a question regarding the use of exceptions at the highest level of a program. I have seen programs using this strategy and I have also seen posts considering this bad practice. However, the posts considering this bad practice have been written in c# or some other programming language, where there are some error handling built in. ...


3

I would go with an assertion. Without any further information, I'd probably default to the non-static assert(). A comment would indeed be wishful thinking. Not only can it be ignored, but it can very easily go out of date if (when?) you decide 32 should no longer be the limit. If this was a public API with other programmers using it, the exception would be ...


6

Clearly in your main () function you don't have a chance to handle the exception in any meaningful way. If an exception reaches main (), all you know is that something went badly wrong. You can of course decide how you want to handle the situation that "something went badly wrong". That's not at all a bad practice. You may of course decide that you handle ...


10

TL;DR: What does the specification say? A technical detour... When an exception is thrown and no handler is ready for it: it is implementation defined whether the stack is unwound or not std::terminate is called, which by default aborts depending on your environment setup, aborting may or may not leave a crash report behind The latter can be useful ...


20

One problem with letting exceptions go past main is that the program will end with a call to std::terminate which default behavior is to call std::abort. It is only implementation defined if stack unwinding is done before calling terminate so your program can end without calling a single destructor! If you have some resource that really needed to be restored ...


4

The moment you know you have to abort, go ahead and call std::terminate already to curtail any further damage. If you know you can wind down safely, do that instead. Remember that stack-unwinding is not guaranteed when an exception is never caught, so catch and rethrow. If you can safely report/log the error better than the system will do it on its own, go ...


4

An exception that you catch gives you the opportunity to print a nice error message or even try to recover from the error (possibly by just re-launching the application). However, in C++ an exception doesn't hold information about the program state when it was thrown. If you catch it, all such state is forgotten, whereas if you let the program crash, the ...


-6

Ultimately, if an exception bubbles up past main(), it is going to crash your application, and in my mind an app should never never crash. If it is ok to crash an app in one place, then why not anywhere? Why bother with exception handling at all? (Sarcasm, not really suggesting this...) You might have a global try/catch that prints an elegant message ...


26

The main reason for not letting exceptions escape from main is because otherwise you lose all possibility to control how the problem gets reported to your users. For a program that is not intended to be used a long time or distributed widely, it can be acceptable that unexpected errors are reported in whatever way the OS decides to do it (for example, ...


2

Well, there are different types of scope-guards you could create, depending on what features you need: Can it be disarmed? That one is free, something along those lines has to be implemented anyway. One cannot depend on RVO always coming to the rescue. Shall it only execute if an exception is thrown? This needs C++17, unfortunately. In any way, there ...


4

Your scope guard has interesting behaviour, and a quick code review could find various issues or possible issues (using the macro takes more code than not using the macro; your macro is flawed because it is a macro and is unnecessary; the gensym macro can't be used two times on the same line, which could happen in macros; many types are not ...


1

Here's my 5 cents of what I haven't seen others mention. When passing around variables you do not want to be passing by value, unless you really need to, to avoid extra constructions and destructions and copies. So unless you really must pass by value, using references everywhere, even if you do not mean to change the passed value is a significant ...


2

There are already some good points, but I think I can add some further thoughts on the matter. If Java doesn't provide a feature that C++ has, it means that the feature is not good, so we should prevent using it. This has been pretty well answered: Java isn't "the good parts" of C++, nor is there any reason to think so. In particular, though the ...


2

In MacOS X and iOS, and with developers using Objective-C or Swift, reference counting is popular because it is handled automatically, and the use of garbage collecting has considerably decreased since Apple doesn't support it anymore (I am told that apps using garbage collection will break in the next MacOS X version, and garbage collection was never ...


1

The biggest disadvantage of garbage collection in C++ is, that it's plain impossible to get right: In C++, pointers do not live in their own walled community, they are mixed with other data. As such, you can't distinguish a pointer from other data that just happens to have a bit pattern that can be interpreted as a valid pointer. Consequence: Any C++ ...


-2

As I can see, smart pointers are used extensively in many real-world C++ projects. True but, objectively, the vast majority of code is now written in modern languages with tracing garbage collectors. Though some kind of smart pointers are obviously beneficial to support RAII and ownership transfers, there is also a trend of using shared pointers by ...


0

You can use macros in C/C++ to change identifiers as needed. For javascript the obvious candidate is var since it is only needed in javascript ... it can be redefined as necessary to any c type. c-header.h //constant integers #define var const int #include "int-consts.js" #undef var //constant strings #define var const char* #include "string-consts.js" ...


0

While extrapolating the "40 LoC vs 200 LoC" example, saying "well, only a fifth of the total LoC is obviously faster to write so it must be better" may seem tempting, I really think there is little truth to be found there. Optimizing for fewest LoC is almost never a good idea in my opinion. Yes, every LoC written is a potential for bugs, and you never have ...


0

You are indeed on the right mental path. When you draw geometry, the vertex shader runs separately on each vertex of the geometry and transforms the positions into clip space, as well as letting you manipulate any associated attributes. The fragment shader is invoked on each pixel that is considered to be covered by the geometry, and the attributes of the ...


25

I've debated whether to bother posting another answer when you already have a number that reach what seem to be entirely reasonable conclusions: that your idea is basically a disaster waiting to happen. I think, however, they've failed to point out some highly relevant reasons behind that conclusion. The differences between Java and C++ run much deeper than ...


4

No, you should generally not write C++ like it was Java, and you should definitely not omit C++ language features that aren't present in Java. For one thing, Java is garbage collected, and thus has no equivalent of the C++ "delete" keyword. Okay, so you implement a program without delete, because per your rules, it's not allowed. Congratulations, you now ...


1

The current answers all say this is a bad thing to do, as you should take advantage of the language you are using and also explain why a C++ feature is not “bad” just because it is not in jave. I will answer this from a different angle. It is one thing to avoid complex C++ feature like multiple inheritance, operator overloading and defining your own ...


10

If you're going to write code in language X, spend the time to properly learn the language and use all the features it offers to help you solve the problem. Bad things happen when you try to do a "word for word" translation from one language to another, whether that's Japanese to English or Java to C++. It's far better to start with a good understanding of ...


6

All of your reasons can be disproved: If Java doesn't provide a feature that C++ has, it means that the feature is not good, so we should prevent using it. It doesn't mean the the feature is not good (no feature can be inherently bad). It only means that the feature was frequently misused (or impossible to implement due to fundamental concepts, like ...


0

No one should be writing any code that other coders don't understand. If you think language lock is a problem, wait until you have developer lock. One is more likely to hold you hostage than the other. There really are no technical reasons. What you've created is a scenario where a language was used for whatever reason, but many current and possibly future ...


74

I will answer your questions in order. If Java doesn't provide a feature that C++ has, it means that the feature is not good, so we should prevent using it. Yes, any feature not present in Java is anathema on the hard drive. It must be burned from your code base. Those who do not obey will be scrounged, their souls used to placate the RAID gods. C++ ...


4

Suppose I am limited to use C++ by the environment in the project. Is it good to prevent the use of some language features that C++ has but Java doesn't have (e.g.: multiple inheritance, operator overriding)? No. If "by the environment of the project" you are limited to using C++, then there is little, if any, point in even thinking about any other ...


26

Java has features that C++ doesn't, like a built-in, fast, reliable garbage collector, a single-root object hierarchy, and powerful introspection. Java's other features are designed to work together with the Java-exclusive features, and many of Java's omissions of C++ features are possible because the new features make up for the lack. For example, Java ...


118

Just because the syntax seems similar on the surface doesn't mean that the two languages are compatible. 1, 4 and 5 are really the same question: Now, I'm no fan of C++, but saying "Code without C++ specific features is usually more maintainable" is just ridiculous - do you really believe that Java got everything right, and took all the good features while ...


54

I'm just gonna answer your reasons: I don't understand how you come to that conclusion. Different languages have different features. Depends on scope, architecture of language, sometimes preferences of creators and many more reasons. Some features of a language may be bad, but your generalization is plain wrong IMHO. Writing C++ just like Java may lead to ...


262

No. This is woefully and terribly misguided. Java features are not somehow better than C++ features, especially in a vacuum. If your programmers don't know how to use a feature, train or hire better developers; limiting your developers to the worst of your team is a quick and easy way to lose your good developers. YAGNI. Solve your actual problem today, ...


3

It is not generally sensible to limit the number of threads, if these threads are used only for concurrency. I.e. aside from the extra resource use, spawning threads is fine to manage blocking operations, increase responsiveness, …. A good example is a web crawler that might want to download multiple small resources, and uses multiple threads to compensate ...


2

For what it's worth, this actually has a semi-practical use. In the scenario you have set up, you can only use objects of type A or B via the interface defined by A. The function B::f is only callable via virtual dispatch, not directly. For example: B * pb = new B {}; A * pa = pb; pa->f(); // fine, calls B::f via virtual dispatch pa->A::f(); ...


1

It's absolutely intentional. Changing the visibility must (at most) change whether your code compiles or doesn't compile. It must never, ever change what the code does. If B::f() were public, then you would expect B::f() to be called. The fact that you made b::f() private cannot change this, according to the rule above; it is only allowed to change whether ...


0

Although technically not completely correct, C++ is still considered a superset of C, was inspired by it and as such appropriated some of its properties, integer division being one of them. C was mostly designed to be efficient and fast, and integers are generally much faster than floating points, because the integer type is tied to hardware, whereas ...


5

This is due to the evolution of hardware. Back in the early days of computers, not all machines had a floating point unit, the hardware was simply not able to understand the notion of a floating point number. Of course, floating point numbers can be implemented as a software abstraction, but that has significant downsides. All of the arithmetic on these ...


7

Why doesn't the compiler understand I want the result to be a decimal number? The C++ compiler is simply following well-defined and deterministic rules as set forth in the C++ standard. The C++ standard has these rules because the standards committee decided to make it that way. They could have written the standard to say that integer math results in ...



Top 50 recent answers are included