It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I've been programming C++ and Java for quite a while now and have some questions about common C++ architecure.
When I program in Java I try to mimic the standard library, that is using interfaces such as Iterable and Serializable and having similar naming conventions and functionality. With C++ however, I hesitate when trying to mimic the STL conventions (with the exception of iterators).
I've boiled it down to the following questions (are the following common convention to implement):
Allocators
Interfaces (classes with only pure virtual methods)
Templates instead of abstract base classes
Restricting exception throwing...
... or having a class optionally throw exceptions (such as in std streams)
Using typedefs for, more or less, obvious types (reference_type, pointer_type, value_type, ...)
Or is the std of C++ not worth mimicing at all?
Thank you for your opinions / answeres!
The more I've used C++, the less fond I am of mimicking the best of libraries I find. The problem comes in when we get a junior developer on the team. They'll understand the basics, but not the subtleties of the language. They may know how to create a map or list using the template syntax, but be unable to understand it when it's applied to another object. The added complexities of debugging and doing code read-throughs also take valuable time away from solving problems or advancing your product.
I have grown to lean towards using the most basic features of the language, which typically leaves the code in a more naturally readable state. I've regretted deviations from this path when I go back 8-12 months later to hunt down an obscure bug with the code.
Java, on the other hand, has more simplistic library implementations that is very well understood by more junior Java developers. I do find that junior Java developers tend to have a greater understanding of the language then junior C++ developers. The being said, C++ developers have more opportunity to become truly competent owing to the lower level of thought needed to become an intermediate C++ programmer.
It greatly depends on your project. The general advice seems to be: Don't bother having a concrete standard for C++.
E.g. with typedefs there are multiple opinions both "for" and "against".
The reason why a concrete coding style for C++ is less important in C++ is because the language does not provide the ways to enforce and check those styles.
I.e. the grammar isn't easily parsable and therefore there are pretty much no tools to meaningfully style-check / refactor C++ code.
Which means that the weight of the style-check falls on the programmer's shoulders. I.e. it makes less sense to enfore style guides, because then much of the time saved by them is wasted in manual style checks.
So just use whatever your project / company uses or decides to use.
Here are my personal preferences:
Allocators: No opinion. If you need a custom allocator, chances are you'll know better than me what to do with it.
Interfaces: If you're doing any performance-sensitive work - don't. They make things noticeably slower in a realtime application. Both abstract virtual classes and the pImpl pattern.
Templates instead of abstract base classes: It depends. But the general opinion seems to be that templates should be used for container-like functionality and a few other simple cases. Otherwise, it's a decent pattern. Debugging these is still a serious pain and will be in the next few years.
Restricting exception throwing: Yeah, do that. Try not to use exceptions, because believe it or not, in 2012 they are still not universally supported.
Using typedefs:: Just try to use c++11's std::auto. Otherwise, they kind of make your life harder because they're halfway to #define macros. I'd personally use an IDE (or Vim) to ease the typing stress of longs names and write the long names.
Related
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 12 years ago.
I'm starting C++ programming in my first job. I'm a CS student and I have learn programming in Java. What advice would you tell me to watch out so I don't cause trouble in my new job?
Would you have any advice or references would be appreciated.
(example: I know C++ is more likely to have memory problem than Java)
Thank you very much!
Maybe you already know this, but one common mistake for folks used to Java and learning C++:
Don't use new unless you have to (and you probably don't really have to). In most cases where you want to create an object, you should just create it "on the stack", like ClassType obj;.
Two things:
Get yourself a copy of Effective C++ by Scott Meyers.
Lint your code. This will not only catch potential bugs early in the development process, but also teach you good coding habits (e.g. declaring a method's input arguments as const references). I use PC-Lint for this.
For me, the biggest difference between Java and C++ is pointers, so I would try to get pointers down. Just my opinion.
No two ways about it. You're going to be a menace until you've been bit enough by C++ gotchas to hate the language. I'd recommend trying to write functions and not classes. A lot of people think OOP is great, but really most users want your code to "do" something, not "be" something. Anyways, good luck. :-)
Definitely what Chance said. Memory management is explicit in C++. I had an excellent textbook in college called Deitel C++. It's a C++ Bible.
I would also learn up on the Standard Template Library and Boost.
This might give you some ideas.
Some important excerpts :
Researchers (Bloom (1985), Bryan & Harter (1899), Hayes (1989), Simmon & Chase (1973)) have shown it takes about ten years to develop expertise in any of a wide variety of areas, including chess playing, music composition, telegraph operation, painting, piano playing, swimming, tennis, and research in neuropsychology and topology. The key is deliberative practice: not just doing it again and again, but challenging yourself with a task that is just beyond your current ability, trying it, analyzing your performance while and after doing it, and correcting any mistakes. Then repeat. And repeat again.
And here is how to do :
Get interested in programming, and do some because it is fun. Make
sure that it keeps being enough fun so that you will be willing to
put in your ten years/10,000 hours.
Program. The best kind of learning is learning by doing. To put it
more technically, "the maximal level of performance for individuals
in a given domain is not attained automatically as a function of
extended experience, but the level of performance can be increased
even by highly experienced individuals as a result of deliberate
efforts to improve." (p. 366) and "the most effective learning
requires a well-defined task with an appropriate difficulty level for
the particular individual, informative feedback, and opportunities
for repetition and corrections of errors." (p. 20-21) The book
Cognition in Practice: Mind, Mathematics, and Culture in Everyday
Life is an interesting reference for this viewpoint.
Talk with other programmers; read other programs. This is more
important than any book or training course.
If you want, put in four years at a college (or more at a graduate
school). This will give you access to some jobs that require
credentials, and it will give you a deeper understanding of the
field, but if you don't enjoy school, you can (with some dedication)
get similar experience on your own or on the job. In any case, book
learning alone won't be enough. "Computer science education cannot
make anybody an expert programmer any more than studying brushes and
pigment can make somebody an expert painter" says Eric Raymond,
author of The New Hacker's Dictionary. One of the best programmers I
ever hired had only a High School degree; he's produced a lot of
great software, has his own news group, and made enough in stock
options to buy his own nightclub.
Work on projects with other programmers. Be the best programmer on
some projects; be the worst on some others. When you're the best, you
get to test your abilities to lead a project, and to inspire others
with your vision. When you're the worst, you learn what the masters
do, and you learn what they don't like to do (because they make you
do it for them).
Work on projects after other programmers. Understand a program
written by someone else. See what it takes to understand and fix it
when the original programmers are not around. Think about how to
design your programs to make it easier for those who will maintain
them after you.
Learn at least a half dozen programming languages. Include one
language that supports class abstractions (like Java or C++), one
that supports functional abstraction (like Lisp or ML), one that
supports syntactic abstraction (like Lisp), one that supports
declarative specifications (like Prolog or C++ templates), one that
supports coroutines (like Icon or Scheme), and one that supports
parallelism (like Sisal).
Remember that there is a "computer" in "computer science". Know how
long it takes your computer to execute an instruction, fetch a word
from memory (with and without a cache miss), read consecutive words
from disk, and seek to a new location on disk. (Answers here.)
Get involved in a language standardization effort. It could be the
ANSI C++ committee, or it could be deciding if your local coding
style will have 2 or 4 space indentation levels. Either way, you
learn about what other people like in a language, how deeply they
feel so, and perhaps even a little about why they feel so.
Have the good sense to get off the language standardization effort as
quickly as possible.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 12 years ago.
For most C++ projects Boost covers a lot of ground component wise but often used solutions and idioms require some boiler plate or ground work. What do you consider so essential that you would have it in every project and thus have it in a small "library"?
Some things I thought of:
Singleton base-class (somebody will think he needs it, so he can do it properly)
ScopeGuard
Factory base-class
any_iterator
(The last two are in Loki but Loki has overlap with Boost and people are hesitant to use it.)
Edit: I might should add that I don't ask about the usual extensions of the standard library e.g. copy_if.
None of the above. In particular, definitely not a Singleton class, since the use of Singletons are typically an indication of a design flaw. In the past 15 years, I have never needed a Singleton class and all those that I have found in my travels were hacks or otherwise compromised the robustness of the system they were in.
Generally speaking, aside from a good, Standards-compliant compiler, a desire to never stop learning more about my language of choice and coding standards that don't restrict my movements, I have found that I need nothing in order to write complete systems.
Of particular note, over the past 15 years every job I've had has specifically forbidden the use of Boost. Although I use Boost in my own projects and in little tools I hack up, none of my production code uses it. I am a fan of Boost, but I haven't really missed it. And now with the C++0x support in VS2010, I miss it even less.
That said, over the years I have cooked up an #include library that I take with me wherever I go of useful little things and gizmos. It includes:
An exception framework
A version of sprintf that works with std::string
A high-resolution timer class which I use primarily for development, stress testing & debugging
An implementation of transform_if
An implementation of copy_if
And a few other STL extensions which I use very rarely.
My small library, that I carry along with most projects contains very practical tools:
assert utilities (release & debug assert with a user dialog with details and buttons for "start debugger", "ignore this assertion", "always ignore..")
Buffer utilities to avoid working with "plain" heap arrays (class HeapBuffer and class SharedHeapBuffer with ref counting)
logging facilities
UTF8 / UCS2 encode/decode
configuration utilities (class CfgValue with one-liner string-to-number/bool conversion methods)
some fast string to number and number to string routines
fast float to int conversion routines
explode/implode numbers/strings on separator utilities
ini file parser & writer
timer class and some quick&dirty profiling tools
mutexes, conditions, r/w-locks, multi-threading utilities (but from time to time I replace more and more of that with boost locks and thread utilities)
a lightweight messaging system "construction kit" (messages, ports, sender, handlers, sinks, dispatchers, routers, threaded sinks, threadpool sinks and so on)
None of the ones you suggested.
A singleton is a horrible antipattern, and the last thing I'd want in my C++ programs is more of them.
And if you use RAII consistently for your own classes, you don't really need a separate ScopeGuard class.
A factory base-class? What exactly would it do? I don't really see enough common functionality between factories that it'd be worth putting in a single universal base class.
And I'm not really sure what you mean by an any_iterator. :)
The things that are essential to a C++ project are the ones people put in libraries.
And if something is not in any of the common libraries, then it is because it is not commonly needed (or because it has to be customized for the individual project, so a library version has little value)
So your question could basically be rephrased as "what would be an obvious addition to popular libraries, which hasn't already been added to them", and the answer, just as obviously, is "nothing, because if the idea was obvious, the library writers thought of it as well, and so they already added it"
Maybe I don't write the sheer volume of code as other people (been using C++ professionally for six years), but I'm going with: nothing. Any time I've wished an idiom was in the standard library or Boost, that's a clue that maybe it isn't the best way to go. Often times you can express your concepts more simply by rewriting them to take advantage of existing constructs. Good code is easy code. Let the geniuses behind Boost take care of the complicated stuff for you.
Ring or circular buffer. This an often used data structure in Embedded Systems.
logging class (that also works in a Gui)
An encryption library or two wrapped up in a nice interface.
Hashing algorithms can also be quite useful.
a good logging mechanism such as Boost.Log or log4cxx
unit testing framework such as Boost.Test or google test
documentation, preferably using doxygen
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 12 years ago.
I've barely/rarely used C++ in the past decade, and now it looks like I'll be doing something in it again. I'm looking forward to it, but have to wonder how it's changed since I last used it.
Are there any good / brief web pages, blog posts, or even books on how C++ has changed in the past decade?
Please note this question is regarding the language as well as tools or any additional information about working in C++. Specifically I'm working in Windows, using VC++2008.
While the official standard hasn't changed much over the past decade or so, there are several things of importance that have happened:
while it's not an official standard yet, an upcoming new standard (commonly called C++0x) is 'around the corner'. GCC and MSVC 2010 have incorporated significant parts of that new standard, but I'm not sure how much is in common use.
the Boost library has become a major player in providing additional support for the language - to the point that it was a significant influence on the new standard
'template-based' programming techniques have become much more prevalent, probably overtaking the older 'inheritence-based' techniques of code reuse (this might have been well underway when you last looked at C++ depending on the practives your shop may have been using at the time).
compilers (and in particular Microsoft's) have come a long way in standards compliance
The biggest change is that C++ standard actually works in all major compilers now. Things like member templates used to be iffy.
The language itself has not changed much. However, the best practices and idioms did a lot.
I suggest you take a look at the book "C++ Coding Standards: 101 Rules, Guidelines, and Best Practices" by Herb Sutter and Andrei Alexandrescu to see how modern C++ looks like today.
I think one of the biggest changes is one of mindset: many people have (finally!) realised that templates are incredibly powerful and don't need to be slow, and use of the STL and boost is much more widespread than 10 years ago.
VS2008 comes with TR1, a large addition to std that contains things like static arrays, reference counting pointers, and suchlike. Apart from that, the biggest change is just that the compiler compiles how the Standard defines.
An interesting question as I'm coming up to my 10th anniversary of programming C++ for coins.
My personal view is that I'd be somewhat wary -- but only somewhat -- since I haven't seen it all (though I think I can guess what it's like) -- of paying strong attention to the internet echo chamber. It's true, some people have gone full bore for the modern style of C++, with everything fully template'd up and using modern techniques to get the compiler doing its Prolog thing to best effect. However this is certainly not universally true, and, in the main, the C++ code I see today is very similar in most ways to the C++ code I saw ten years ago.
It would be a good idea to brush up on modern fashions, because some stuff that was somewhat rare ten years ago (smart pointers, regular use of RAII, standard library containers and stuff) is now more common. But unless you are sure that the code you will be working with is festooned with templates and boost and so on, you stand a good chance of working with something that's at heart very much like what you used to work with.
It may be unfashionable to say it, but that doesn't make it any less true: regardless of skill level, lots of people don't care for modern C++. Some, because they don't understand it. Some, because they do understand it. And for some, perhaps "care" isn't even the right word -- they don't even know it exists. And as you might expect these people all code accordingly.
Perhaps I move in the wrong circles, but my experience has been people who don't or can't or won't code in the modern style outnumber those that might do by some vast margin. And those who might do, generally don't, because they're outnumbered. Their code gets rewritten, or ignored, until they start writing stuff that other people can understand. So maybe this is good, or maybe this is bad -- it's hardly relevant, in my view, because the outcome is the same: that if your experience turns out to be anything like mine, you have a good chance of encountering today code that's remarkably similar to what you would have seen in 1999.
P.S. Nicolai Josuttis has written a couple of books that my last employer's resident template expert seemed to like. Also try Modern C++ Design (Alexandrescu) -- probably a bit dated now, but it explains many of the principles. Herb Sutter's Exceptional C++ gives, as I recall from a skim of a work copy, a good overview of some modern techniques without going too nuts on the template front. And of course boost demonstrates all this sort of thing (and much, much more -- then some bonus material) put into practice over a range of compilers.
(Hopefully the above list is not too dated; as my answer might suggest, I have found much less of a need to keep up to date with the latest trends in C++ than I would ever have expected.)
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 12 years ago.
What does C++ add to C?
What features of the language are the Clang/LLVM projects, the parts of GCC that are being written in C++, chromium, and any others all taking advantage of? What features are they avoiding?
Like all sophisticated and powerful things there is a price to be paid to succeed in C++.
You have to be incredibly careful with memory management.
Multi-paradigm capability means you have to be really good at design to avoid making a mess.
Extreme performance requires careful planning and selection of features used.
The ability to circumvent most every language policy requires monumental self discipline.
So if you're sloppy with memory, poor at design, don't need fast programs, or have no self discipline, then please don't learn C++. There is always Java or C#.
meta programming? templates?
like with C you get performance, but the code looks horrible.
with the high level languages you get nice code but there is less flexibility to make the fastest possible code.
with c++ you can do both? you can freely make anything as fast as it could be made in C, but native object orientation, and templates/operator overloading ect makes it so you can write fairly nice looking code too. indeed, you can make it so it is neat and fast.
I have never really found it more of a pain to write stuff in c++ than in a higher level language. the trick is having good libraries.
Because despite academic efforts such as Singularity, there's not a single mainstream OS where drivers can be written in a high-level language.
Note that anything that can be done in C++ can also be done in C, but some things are a lot easier in C++.
Not? I would say it's not worth if you performance is not an issue for you. (Follow the double negatives.)
My two cents:
Although I don't program in Python, I would have to say that Python is probably the best programming language for getting real work done. It's an elegant language, and it has an enormous collection of libraries for doing various things. However, my experience as a user has shown me over and over again that Python is slow (take yum, for example).
I do know Haskell pretty well, and I have to say that it's a friggin' awesome language. Better yet, it is compiled, and its speed is competitive with Java and C++ (though you have to put forth extra effort to get this speed in some cases). However, libraries for things like database access don't always match the elegance of Haskell's base libraries (I'm probably way wrong about this), and they're harder to install on Ubuntu. In my opinion, that's why it's more challenging to get real work done in Haskell than in Python.
Ruby's good for web applications. Other than that, it's slow (though I speculate jRuby or something might be faster).
C++ is far from elegant, and in many cases, elegance is frowned apon. Anyone ever told you to use static_cast instead of C-style casting? Anyone ever told you not to use namespace std;? C++ has a lot of features, but doesn't tend to have many important language features (such as closures, which are formally proven to be the best thing since sliced bread).
Why do people use C++, then? Well, it's performance-focused, making it a good choice when you need speed. It has classes, namespaces, and templates, so it's a good choice when you want better code organization, but still need to use "C" for some reason. Also, it has the Boost library, which I've heard is really good for getting work done.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
C++ has too many features, and I can't see how any programmer is able to remember all these features while programming. (We can see how this affected the design of newer languages, such as Java)
So, what I need is a list of features that are enough to know, disregarding all the others, to create c++ programs, perhaps created by someone who thought the same way as I did.
Hope I was clear enough.
Learn Resource Acquisition Is Initialization.
The technique was invented by Bjarne Stroustrup, to deal with resource deallocation in C++.
[...]
RAII is vital in writing exception-safe C++ code: to release resources before permitting exceptions to propagate (in order to avoid resource leaks) one can write appropriate destructors once rather than dispersing and duplicating cleanup logic between exception handling blocks that may or may not be executed.
C++ is an object-oriented language with features like inheritance, encapsulation and polymorphism that is also found in popular languages like Java, C# etc. C++ also features generics via templates. However, in C++ you have to explicitely handle memory deallocation (ie. no garbage collection). This makes it very important to be able to release resources and deallocate memory in a controlled manner, and that is why I believe RAII is a very fundamental concept in C++. You will have a hard time understanding a "smart pointer" unless you understand RAII.
This is really an impossible to create list. Every place I work has a different acceptable subset of C++. So its going to be different depending on what you're developing on. I've seen C++ that truly is just C with occasional use of the "class keyword" to very run-time polymorphism oriented code to template meta-programming heavy code. Then the practices are going to change based on what frameworks/libraries/platforms you are targeting.
The best I could suggest is reading various coding standards and seeing the how they suggest you ought to write code using C++.
Google's Coding Standard
Sutter's Coding Standard Book
You learn and remember them by having a need for them. I'm not sure what sort of "features" you're looking for. "virtual functions" are definitely something you want to learn, but I don't really know your background. Should I be suggesting polymorphism/class inheritance too? Template classes/functions?
I think templates are such a feature...
Do you have a tool box containing too many tools? Then don't use them all? Use the ones you need.
Read a good book with C++ best practices and design patterns.
Don't be in too much of a rush to master a language. Peter Norvig (of Google) argues that it takes about 10 years to gain a mastery at anything.