Domain: cppreference.com
Stories and comments across the archive that link to cppreference.com.
Comments · 38
-
STL & Boost
As far as I'm concerned, the language went off a cliff when it started incorporating elements of STL in its basic definitions. One good example of this is the ranged for loop, introduced in C++11, which requires iterators that conform to APIs established in the STL. IIRC, these are statically bound to the for operator, which prevents developers from leveraging inheritance and polymorphism when designing their own iterators.
STL was a great improvement in its day, but I haven't been a fan for years, nor for Boost. Both are often cryptically written, poorly documented, and overly abstracted compared to modern frameworks. But, instead of improving on these standards with lessons learned from more recent efforts with languages and development kits, the C++ standards committee has doubled down on antiquity.
I haven't looked back. -
Re:I am also terrified... by Rust!
The use of a named class versus a compiler generated one to me makes code a bit more readable. This isn't a C++ issue, but I was recently working with a developer on my team who was using the Java lambda `functionality. A framework component in our code base expects to get a function to process some data with and the architect's examples used the lambda. This developer followed the example but because of the requirement for "virtually final" data inside the scope block, he could not get his code to work or compile. He was heading down the path of a complete rewrite and SQL stored procedure changes to get it fixed.
I sat with him for about 20 minutes told him to just create a private inner class that implemented his function interface, where the constructor passed in the external data it needed and had a method to return the response. Then he moved all of the lambda code into this class, created a single instance, passed it to the call back and pulled off the response. Everything worked.
C++ obviously isn't saddled with the baggage Java has where new constructs like this require the captures to be "virtually final" but the details about the captures in C++ can be every bit as confusing.
So a simple class that implements an interface, accepts the "captures" as input arguments which can be passed by reference or pointer, does the same thing as the lambda but just feels cleaner. Lisp lambda's feel right, C++ and Java are not Lisp but Phil Greenspun's 10th rule is really starting to show:
"Greenspun's Tenth Rule of Programming: any sufficiently complicated C or Fortran program contains an ad hoc informally-specified bug-ridden slow implementation of half of Common Lisp
But for those who fully grasp the syntax and rules around the captures and the like, and prefer to use the lambda's they should. I do use them in some basic instances, much like I use basic container classes, so for things like providing functions to a looping iterator. But anything more complex I prefer simply creating a new class that will implement the required interface and working from that.
-
Re:Indeed. C++ is a better C
Constexpr functions were a big step in the right direction here, letting you move between compile-time and run-time computation without shifting syntax, but there's still no equivalent for data.
yes, there is: http://en.cppreference.com/w/c...
-
Re:C-style enum vs C++11 enum class?
Why do you consider the first sample wrong and the second one fixing it?
Please go educate yourself about C++11 scoped enumerations. Basically C-style enums allow implicit conversion to and from integers, but C++11 scoped enumerations require explicit conversions. The feature was added to make it possible for the compiler to reject code with this type of bug.
That's what fixes the bug in the grandparent post: in the old style enum example, the function expecting ViolationFlags can be passed an enum of type VirusCheckerResult, and the compiler happily inserts implicit cast through int. Changing "enum" to "enum class" requires you to use the correct type, so the compiler will generate an error if you try to pass VirusCheckerResult to a function expecting ViolationFlags.
tl;dr: Unlike old-style enums, C++11 scoped enumerations are more than just window dressing for integers.
-
Re:Missing generation of academics...
Dots are not operators in ANY OOP language you silly fuck!
-
Re:Relevant in an intro programming course
To assist reading, I would prefer using keywords. For example, 'not A and B' rather than '!A && B'. It seems to improve readability, less error prone (no accidental 'A & B', which is 'A bitand B' with keywords).
I don't know your teaching methodologies, but please watch the Stop Teaching C presentation by Kate Gregory, where she shares her experience on teaching C++ and how to make it less confusing for novices.
-
Undefined behavior
Not quite, it is in fact undefined.
C++ is the post-increment operator, it increments the variable, but then returns the original value. Therefore, since C started out as 0x11, C++ will evaluate to 0x11 while modifying C to be 0x12 as a aside effect.
Therefore, if you were > optimistic you could try to claim that "C++ < C", expecting the operations to be evaluated left-to-right and thus be evaluated as "0x11 < 0x12". However, C++ doesn't specify the evaluation order of operators, which means that "C" might end up being evaluated before "C++", in which case the comparison would be evaluated as "0x11 < 0x11" instead. The only thing you can be sure of is that C++ will NOT be greater than C.
Basically, as a rule of thumb you should never modify a variable within a line of code if the value of that variable will matter anywhere else within that same line. http://en.cppreference.com/w/c... - discusses undefined behavior halfway down the page.
-
Re:More features.
I honestly couldn't say. I learned C++ about 20 years ago, hated it, tolerated it a bit while working on LLVM, revisited it in C++11 and discovered that the language had changed beyond all recognition and didn't suck anymore. I like cppreference as a reference for the standard library, but I've not used a tutorial (and I definitely wouldn't recommend the old book that I read).
-
Re:More features.
Really? Prior to 1998, there was no standard library, though the Standard Template Library from SGI was pretty much treated as the standard library. When C++ was standardised in 1998, most of the STL was incorporated into the C++ standard library, so almost everything that you'd learned from the STL would still be relevant. The next bump to the standard was in 2011. Lots of stuff was added to the standard library, but very few things were changed in incompatible ways (auto_ptr was deprecated, because in 13 years no one had figured out how to use it without introducing more problems than it solved) and almost all C++98 code compiles without problems against a C++11 library. C++14 and C++17 have both added a lot more useful things but removed or made incompatible changes to very few things.
Let's look at a commonly used class, std::vector. The only incompatible changes in the last 18 years have been subtle changes to how two of the types that are accessible after template instantiation are defined. Code using these types will still work (because the changes are not on the public side of the interface), but the chain for defining them is more explicit (e.g. the type of elements is now the type of elements, not the type of things allocated by the thing that allocates references - code would fail to compile if these weren't the same type). The changes in std::map are the same.
That said, you do need to learn new things. Modern C++ shouldn't use bare pointers anywhere and should create objects with std::make_shared or std::make_unique. The addition of std::variant, std::optional, and std::any in C++17 clean up a lot of code.
-
Re:Memory-unsafe is a BS meme
Range checking for things like std::vector is turned on by default in recent compilers.
ie. "array[-1] = 0x666;" will throw an exception, just like in Java.
This is absolutely wrong, and would violate the C++ standard if it wasn't. http://en.cppreference.com/w/cpp/container/array/operator_at
-
Explicitly destroying objectsI'm working in Unix and Network programming and also Systems programming, and I made an early habit of explicitly destroying / releasing / closing resources that are not needed anymore, even when they are reclaimed by the OS when the program exits. This includes in particular open files, and all kinds of network descriptors. Why? Because most of my code usually ends up repackaged into libraries and reused inside longer running programs (i.e. inside loops); and not being disciplined about releasing resources would result in all kinds of leaks. This is particularly bad when that code gets reused inside device drivers.
Of course, things got a lot easier once I switched from C to C++ and the STL and RAII idiom, but trying to release resources is still ingrained in my muscle memory; it takes a conscious effort in C++ NOT to explicitly release a resource acquired through initialization.
-
Re:Big pile of mess to clean up
-
Re:Big pile of mess to clean up
-
Re:Big pile of mess to clean up
> a programming language so crude it does not even have a concept of an array, and hence bounds checking
Obviously, http://en.cppreference.com/w/c... doesn't exist in your world.
-
Re:They've only just discovered this?
On error, dynamic_cast returns NULL for pointers, and an exception for references. From cppreference:
If the cast is successful, dynamic_cast returns a value of type new_type. If the cast fails and new_type is a pointer type, it returns a null pointer of that type. If the cast fails and new_type is a reference type, it throws an exception that matches a handler of type std::bad_cast.
-
Re:Surprise?
I think you are talking about multithreading in your pigeon English.
Fuck sakes, he was most likely referring to threads.h , which is the std. C++ library for multithreading.
-
Re:Knowing when not to
The main reason for using templates should be to eliminate copy-and-paste coding, not to improve performance.
This depends on the task. Ever heard of expression templates or partial template specification ? Specifically, the latter is used in many std::copy implementations to do a fast memcopy when the data can be identified as POD or scalar that doesn't require the execution of a copy constructor.
-
Re: I would suggest the stl
Agreed that CUDA and OpenCL are great secondary and tertiary ways of heterogeneous multi-core programming.
Not sure what your beef again OpenMP is. OpenMP makes it trivial to add multi-threading to your app.
When did C++ get thread control again? Oh yeah, it wasn't until C++11 and you STILL had to wait for compilers to implement it. In the mean-time OpenMP was already here, and working for years. Considering OpenMP has been around for 18 years, calling it a hack when C++ ignored the whole standardization of multi-threading for YEARS is pretty fucking arrogant -- especially when Intel's, Microsoft's and GCC's compilers have natively supported OpenMP for years. What were Windows users supposed to use in the mean-time for portability? A port of pthreads wasn't even available for Win32 until ~2001 if this page is correct.
There are problems with std::future as this committee paper points out:
* N3964 (March 2014)
Even co-routines are still relatively new:
* N4134 (Oct 2014)
C++11 std::thread is great for the future. OpenMP was a perfectly fine solution when C++ didn't even have one back in the day.
-
Re:Given how C++ is taught.
see, for example, std::make_shared. http://en.cppreference.com/w/c...
-
Re:slashdot and languages
You should read this:
http://en.cppreference.com/w/c...
If no user-defined constructors of any kind are provided for a class type (struct, class, or union), the compiler will always declare a default constructor as an inline public member of its class.
So your Because: it has no ctor!! is definitely wrong. There are no structs, classes, or unions without a constructor. Never. Right is that i in B is not initialized because:
If the implicitly-declared default constructor is not deleted or trivial, it is defined (that is, a function body is generated and compiled) by the compiler, and it has exactly the same effect as a user-defined constructor with empty body and empty initializer list. That is, it calls the default constructors of the bases and of the non-static members of this class.
i is non-static, but a POD type -> no constructor, no default initialization. D has a constructor, which initializes s and calls the implicitly-declared default constructor in B, but this still does nothing for i, since B's default constructor is trivial:
Trivial default constructor
The default constructor for class T is trivial (i.e. performs no action) if all of the following is true:
- The constructor is not user-provided (i.e., is implicitly-defined or defaulted)
- T has no virtual member functions
- T has no virtual base classes
T has no non-static members with brace-or-equal initializers. (since C++11)
- Every direct base of T has a trivial default constructor
- Every non-static member of class type has a trivial default constructor
A trivial default constructor is a constructor that performs no action. Objects with trivial default constructors can be created by using reinterpret_cast on any suitably aligned storage, e.g. on memory allocated with std::malloc. All data types compatible with the C language (POD types) are trivially default-constructible.
i is in B as uninitalized as it is in D. No difference.
-
Re:Write-only code.
dynamic_cast: http://en.cppreference.com/w/c...
-
Re:Good grief...
I wasn't saying the XOR trick is illegal in C++. (It does, however, rely on implementation defined behavior, so you likely couldn't use it in a strictly-conforming program.)
I was saying that it's illegal for the compiler to undo bad data structures, such as replacing your XORed pointers with proper prev/next pointers. If you have something like this:
struct ugly {
uint64_t prevnext;
};Where 'prevnext' is the XORed pointer, the compiler isn't allowed to replace it with something more sane like:
struct ugly {
ugly *prev, *next;
};...or even...
struct ugly {
uint32_t prevnext;
};...if it figures out you picked an oversized integer for the storage.
TheRaven64 pointed out some cases where it can be legal for the compiler to rearrange / modify bad structures, but the gains tend to be minimal.
As I recall, the C++ standard does put some requirements on structure layout, as least for standard layout PODs:
* Minimum size of 1 for a structure so that each element of an array of empty structures has a distinct address
* Distinct addresses for all non-bitfield members
* Pointer to struct is convertable to pointer to first member and back
* Increasing addresses for members in order of specification
* Optional padding as required between members and at the end of the structure.
* Layout compatibility between identically declared standard-layout structs for their common initial sequence. (That's a mouthful!)
(There may be some others I'm forgetting... That list was off the top of my head.)
If a compiler wanted to rearrange a structure (say, to eliminate or minimize padding, or to eliminate unused members), it'd have to prove that the program didn't rely on any of the guarantees the standard offers that the compiler's otherwise violating. Violations of the standard by the optimizer are legal as long as you don't get caught.
;-) -
Re:Is FORTRAN still winning? Was Re:Poor Alan Kay
That is true. My original guess was the memory allocations alone could explain the speed difference. Someone pointed out the handicap to compiler optimizations due to aliasing. (I do not have formal education in comp sci, so I have only a fuzzy understanding of aliasing).
It just means that more than one name can refer to the same memory location. This causes problems for the optimizer which was a big reason why FORTRAN was faster for certain types of computations. It is why the restrict type qualifier was added to C.
-
Re:Problems in C++
Say hello to my little friend: http://en.cppreference.com/w/c...
-
On technical questions
I do think you should be able to list all major STL container classes when interviewing for a C++ programming position. This is akin to being able to read, as you would not even know what to search for otherwise.
I then ask candidates about the data structures the containers represent: memory layout and consumption, optimal usage, etc. Note, this is not about having to remember N overloads of the insert() member function, but rather about knowing what the container does and how to use it optimally.
-
Multiple Return Types?
c++11 added attributes which is kind of what you want, I think. Except there are only 3 standard ones and compiler-specific ones are namespaced.
-
Re:STL is painful to use
Suppose you want to determine if a collection c contains an element e. In any other language, you'd write something like c.contains(e).
I have good news for you! Sure, you still need to provide begin() and end() to specify a range, but it's a step forward. And, with the new non-member begin() and end() you can even use it on plain arrays.
Yeah, you still have to put all the pieces together yourself, but the pieces are a bit more uniform now and there's usually fewer to worry about. (Especially now with auto.)
-
Re:STL is painful to use
Suppose you want to determine if a collection c contains an element e. In any other language, you'd write something like c.contains(e).
I have good news for you! Sure, you still need to provide begin() and end() to specify a range, but it's a step forward. And, with the new non-member begin() and end() you can even use it on plain arrays.
Yeah, you still have to put all the pieces together yourself, but the pieces are a bit more uniform now and there's usually fewer to worry about. (Especially now with auto.)
-
Re:Monty Python Reference
I was thinking the C++ standard library should take care of it.
-
Re:C is the epitome of a programming language.
> Wow are you behind the times. int64_t is where it's at.
I am quite aware of int#_t.Let me know when ALL Canonical C, C++, GNU GCC and MS have _standardized_ formatting names. Instead we stupid shit like this:
uint64_t a = 123;
printf( "%u", a ); // doesn't work
printf( "%llu", a ); // only works with gnu gcc
printf( "%I64d", a ); // only works with MS> Hell, that's part of C99, iirc.
ONLY if you #include which is retarded. Those types should be _native_.I want to tell the compiler that "long long int" is _deprecated_ so that any _legacy_ code I'm compiling with will give me an warning AND/OR error.
> C++ does have type-safe macros.
Lol, uhm, no. Templates are STILL half baked. Let me know when you can do efficient double-dispatch with them. (No cheating by providing Alexandrescu's over-engineered solution from "Modern C++ Design")The C preprocessor is like wise retarded.
#if _DEBUG
// allow all calls to Log::print
#else
#define Log::print(...) // doesn't work because the preprocessor is stuck in 1970s ...
#define Log$(x) Log::print(x) // stupid preprocessor
#endif
class Log {
static void print( const char format, ... );
};
void main()
{
Log foo;
Log::print( "log1" );
Log$( "log2"
}> #pragma is, be definition, vendor specific. I can only assume you're trying to troll.
Calling someone a troll because you don't understand Real-World problems doesn't make it one.I want _standardized_ pragmas for output, and alignment.
#error "Message"
#warning "Message"
#info "Message"
#align(16)GCC gave us this crap fest:
struct foo __attribute__ ((aligned (8)));Fortunately C++11 has the cleaner 'alignas'
... again, C++ solving real-world problems 20 years later!
http://en.cppreference.com/w/cpp/language/alignas -
Re:Any rational programmer is anti-JS
I mean, where's your GC?
-
Re:C/C++
http://www.cppreference.com/ comes in very handy for looking up STL stuff quickly.
-
Re:Wow, that's a big fat ASS^H^HPI
And a stripped-down non-existent API is a way to make things simple?
No, quality != quantity, let's compare the C++ STL to the standard Java libraries. The STL is quite succinct, the standard Java libraries are outrageously bloated. Arguably, the standard Java libraries can do more, but god forbid if you ever actually want to use part of it that you're not already familiar with, as there'll be at least half a dozen slightly different ways to do what you want to do, 90% of which are obtuse and half of which are deprecated. In the time you spent searching for something suitable to use in the standard Java libraries, you could have written the same functionality yourself twice, taken a nap, gone grocery shopping and played 36 holes of golf. To add fuel to the fire, because the standard Java libraries are so bloated, it's not even feasible to actually know more than perhaps 5-10% of them, at most. In sharp contrast, the STL can be learned in it's entirety within a few hours.
The STL has the map container, the standard Java libraries have approximately a dozen map implementations, each of which is subtly different, but in ways that don't matter 95% of the time. Of course, for the other 5% of the time when you find out that you've picked the wrong map implementation, %s/Hashtable/HashMap/g will probably break things anyways, despite the fact that they're essentially the same.
The STL has the pair container, the standard Java libraries (as far as I can tell) do not have a pair implementation. How they managed to write approximately a trillion and one standard classes without thinking "Hey, a pair class could be useful!" is beyond me.
The STL has the list container, the standard Java libraries have at least a dozen different lists that can't easily be converted between one another, and classes will randomly only use a small (and inconsistent) subset of these lists.
Why should a programmer have to re-write common routines and data structures for every program?
They shouldn't, they also shouldn't spend more time scouring through documentation than coding.
-
For what it's worth
C++ does have such statements: http://cppreference.com/cppalgorithm/index.html. Check out "for_each" for an example.
-
You'll Miss the APIFirst off, you're going to miss the Java API. I just spent the last semester in your predicament. I have a strong Java background, but I was forced to TA an intro to C++ class. I found that our text "C++ Effective Object Oriented Software Construction" by Kayshav Dattatri was a very good intro to C++ if you've got a Java background. He tends to make comparisions to Eiffel or Smalltalk, but Java comes into the picture often (and its pretty close to Smalltalk in a number of ways).
Also check out www.cppreference.com. I have found it to be significantly more useful than the STL reference at SGI.
To paraprhase Mark Twain, the rumors of the performance of C++ have been greatly exagerated. The advantage you get from cross platform compatibility and a fantastic API far outweigh a minor performance hit.
-
Re:Ask Slashdot: where Google Morons ask questions
The link in the above post (see parent) seems to be broken for me. I don't know if this happens to be the same book as the one above...
This is the book that my Survey of Programming Languages professor suggested for those of us who came in knowing Java but not C++.
It's nice in that it compares and contrasts many features of both languages (including quite a bit on the STL and writing templates in C++), but I found myself wishing it would have gone into more detail several times - my one gripe is that it doesn't do much more than scratch the surface in several instances.
(apparently, there's at least a couple of "C++ for Java Programmers" books on amazon alone...)
A couple of reference sites I've used in the past:
(Personally, I still shy away from C++ whenever I can...I certainly haven't gotten a comfortably firm grip on it yet.)
-
For a C/C++ library reference
I find Cppreference.com to be very simple and to the point. It's got information on both the standard C library, the C++ STL, and a few other common core components of both C and C++. Definitely just a lookup resource for people already familiar with one or both languages, and not entirely complete, but a quite useful resource nonetheless, especially for mundane but necessary things like function names and parameter order/datatype.
-
Re:STL documentation
CPPReference.com is also a very nice ref site.