News for hackers. Stuff that matters.
Re:We have C++14 by astrodust on Monday August 18, 2014 @04:00PM (#8194312)
In languages like C++ "verbose" means "specific and obvious" which is something you want to have when writing certain kinds of code.

It's annoying, it's a drag on productivity, but in the long run it's arguably necessary.

Some other languages which reduce verbosity by making more things implicit make it harder to understand what's actually going on behind the scenes. You lose a lot of information.

Re:We have C++14 by ajuc on Monday August 18, 2014 @04:19PM (#8194420)
A lot of C++ verbosity comes simply from bad defaults. Const and virtual should be the default for example, not the other way around. Would stop the virtual destructor ommision problem, and if you need efficiency you could make destructors non-virtual.

Also in the "hiding stuff behind the scenes" department C++ is quite bad.

    SomeClass someMethod(SomeClass a, SomeClass b) {
        ...
    }
is doing a lot behind the scenes. Code below is better but it's longer and less convenient to write.

    const SomeClass& someMethod(const SomeClass& a, const SomeClass& b) {
        ...
    }
And actually C++ code isn't easy to reason about wihtout reading the whole program. It isn't even easy to parse.

What's going to happen when you run this?

    y = f(x);
It may be that f is function, or a type. f may return the correct type to assign to y, or it may return something else and automatically run some conversion. There may be copy constructor and some destructors involved if it's returning object and not reference. It may run overloaded operator= and do anything at all, for example add f(x) to y. Hell, f can also be a class with operator() overloaded, and you would need to track its state to see what will happen.

And we haven't even touched the subject of #define.

It's much easier to reason about Java code for example.

Re:We have C++14 by wfunction on Monday August 18, 2014 @04:31PM (#8194491)
Uh, no, "virtual" should absolutely NOT be the default. I don't know where you got that idea from (Java?) but it's absolutely horrible.
Re:We have C++14 by dasmithii on Monday August 18, 2014 @06:07PM (#8194980)
I wouldn't call it 'horrible', but rather, inconsistent with C++ and its target area.

Zero-overhead abstraction is a key talking point of the language. Virtual-by-default would contradict this entirely.

Re:We have C++14 by zak_mc_kracken on Monday August 18, 2014 @07:58PM (#8195337)
It was the right default twenty years ago for performance reasons.

These days, the economy of a vtable pointer is not really a good reason, and all languages that have the opposite default (such as Java, as you point out) are doing quite fine.

Because of this default, I can't count the number of times where I've seen "#define private public" and other horrors that developers used to be able to extend classes that their creators were too short sighted to design properly.

Re:We have C++14 by jonstewart on Monday August 18, 2014 @08:22PM (#8195412)
I'm very glad that virtual is not the default. Most of the classes I write are simply value classes and do not use inheritance at all. Once you start using virtual, you really have to embrace traditional inheritance idioms whole hog, and then you've got std::vector<std::shared_ptr<Foo>> instead of std::vector<Foo>.

If anything, the performance difference between std::vector<shared_ptr<Foo>> and std::vector<Foo> is even greater today than it was twenty years ago.

Re:We have C++14 by ufo on Tuesday August 19, 2014 @01:10PM (#8198496)
On the flipside, if you are not using inheritance then you could have solved the same problem with abstract data types. The only big problem is that in C++ the method call syntax is much more convenient to use: foo.frob() vs Foo::frob(foo). IMO, the correct way to fix this is by adding syntax sugar to the language, not by making methods non virtual by default.
Re:We have C++14 by jonstewart on Tuesday August 19, 2014 @01:57PM (#8198785)
I don't understand. Do you mind elaborating? Not sure what you mean, specifically, by "abstract data type" (I think of ADT as just another synonym for a class), nor do I get the static method thing. If you were calling hard-coded static methods, you wouldn't have polymorphism anyway, so how you have virtual methods?
Re:We have C++14 by CJefferson on Tuesday August 19, 2014 @04:40AM (#8196455)
The real problem with defaulting to virtual isn't the vtable pointer, it's the lack of inling.

Not being able to inline a method like (from vector)

    T& operator[](size_t pos)
    { return data[pos]; }
Would kill performance.

In languages which do run-time optimisation you can inline such methods later, but in C++ that's not possible and proving when you can de-virtualise a method (which most compilers do) is very hard and often fails.

Re:We have C++14 by ajuc on Monday August 18, 2014 @04:37PM (#8194517)
Why would it be bad? You could always add non-virtual (inline maybe? it's already useless keyword) if you need the performance, and most of the code doesn't. And it's a source of errors.
Re:We have C++14 by ixtli on Monday August 18, 2014 @04:46PM (#8194574)
Because if the compiler can not figure out how to de-virtualize your usage of a structure then you're going to necessitate that a vtable be created at compile time and used at runtime.

The reason the previous commenter asked if you're from the java world is because in many highly important areas, the effect on memory and speed this would cause would be unacceptable. These areas _tend_ to be left to people who understand languages like c, though, so a lot of newer languages make decisions ignoring these good use cases.

Re:We have C++14 by ajuc on Monday August 18, 2014 @05:04PM (#8194667)
I don't know which world I'm from. I mostly program (for money) in java nowadays, but I also did C++ for money for like 6 years, and I knew C years before. And mostly I've learnt programming on turbo basic and turbo pascal. But never had to do system programming.

Also I don't think it's that big of an achievement to understand C. Despite its flaws it's very simple language, very different from C++.

To the point - you could ensure that compiler can de-virtualize your usage of structure (or class if you will) by adding "nonvirtual" to every method it implements or derives. I don't see how it's any better than having to delete "virtual" from every method it implements or derives. Just a question of defaults, and I'd say most of modern C++ code isn't written with the performance goals that justify nonvirtual as default. You can and should profile after writing something anyway if you care about performance.

And anyway if you have derived classes it's almost always the case that you want at least some of your methods virtual, otherways what's the point?

Re:We have C++14 by kristiandupont on Monday August 18, 2014 @07:56PM (#8195330)
>I'd say most of modern C++ code isn't written with the performance goals that justify nonvirtual as default

I am using C++ right now for embedded code but otherwise I write mostly Javascript. There was a time when C++ was the standard choice of language for desktop apps etc., but that's hardly the case any more. You choose C++ if you need performance and control. And I think the "default means the least overhead" concept makes a lot of sense there.

Also, inheritance is a very central part of mostly all Java code whereas it's much less idiomatic (modern) C++. In C++, classes serve to give you RAII and you specialize with templates.

Re:We have C++14 by pmelendez on Monday August 18, 2014 @06:12PM (#8195001)
>"To the point - you could ensure that compiler can de-virtualize your usage of structure (or class if you will) by adding "nonvirtual" to every method it implements or derives."

Think it in this way. Many respectable people has been making a case to avoid inheritance[1][2]. What you are proposing would actually be an incentive to them. I don't know about you but the amount of functions that I actually override in my code is not even close to the 20%.

Why should we set a default for that 20%?

[1] http://channel9.msdn.com/Events/GoingNative/2013/Inheritance... [2] http://www.gotw.ca/publications/mill07.htm

Re:We have C++14 by ajuc on Monday August 18, 2014 @06:40PM (#8195106)
I agree with "composition over inheritance", but I disagree with "inheritance is evil". Composition over inheritance means you divide you classes into parts that ALSO use inheritance and virtual methods, you just don't make the hierarchy deep and don't mix many different subdivisions into one hierarchy. The problem isn't virtual methods, it's too many divisions and responsibilities in one class hierarchy.

And you do want to refactor your virtual methods and then extracted methods do usually need to be virtual, even if at first they don't they may need to become virtual in future, and IMHO it's better to just make them virtual from the start, if you don't REALLY need the performance.

You can mess up because of nonvirtual-by-default too, especially in C++ because of the difference between stack and heap objects.

    struct A {
       virtual int f(int x, int y) { return g(x,y); }
       int g(int x, int y) { return x+y; }
    };
    struct B : public A {
       int f(int x, int y) { return g(x,y)+1; }
       int g(int x, int y) { return x+y-1; }
    };
    B* b1 = new B();
    A* b2 = b;
    B b3;

    b1->f(2,2); // 4
    b2->f(2,2); // 5
    b3.f(2,2); // 4
This bite me a few times in C++.
Re:We have C++14 by slavik81 on Tuesday August 19, 2014 @03:16PM (#8199212)
Those actually all return 4. Since f is virtual in the base class, it remains virtual in all derived classes, regardless of whether they say so explicitly.

The override keyword was added in C++11 to help prevent the sort of mistake you were trying to show. Any methods you mark with it will result in a compile error if they are not actually overriding anything.

For example, if B::g were marked as override, it would fail to compile because A::g is not virtual.

Re:We have C++14 by danieldk on Tuesday August 19, 2014 @01:48AM (#8196148)
Many respectable people has been making a case to avoid inheritance[1][2].

Unfortunately, class inheritance is the only way to create the equivalent of an interface or (Scala-type) trait in C++. So, even if you avoid class inheritance in general (which is a good thing IMO), you still end up doing inheritance if you want run-time polymorphism in the form of abstract classes or abstract base classes.

Re:We have C++14 by wfunction on Monday August 18, 2014 @05:20PM (#8194755)
Performance is only one side of it. The bigger reason is http://stackoverflow.com/a/814939
Re:We have C++14 by zak_mc_kracken on Monday August 18, 2014 @08:01PM (#8195357)
Over 20+ years of development, I've found this objection to be vastly theoretical and with no practical consequences.

In practice, most classes are designed without inheritance in mind and yet, being able to extend and override them has proven infinitely more valuable than the occasional case where such an overriding breaks the parent class.

The practical reality is that even if a class is not designed for inheritance, inheriting from it is unlikely to break it but very likely to make its user's life much, much easier.

Re:We have C++14 by wfunction on Tuesday August 19, 2014 @12:07AM (#8195991)
Seemingly off-topic, but I'm curious -- what language has the majority of your 20+ years of development been in?
Re:We have C++14 by zak_mc_kracken on Tuesday August 19, 2014 @12:56AM (#8196073)
Professionally, Java for most of the time. Recreationally, Scala and Haskell. I did about 5 years of C++ overlapping with Java before that.
Re:We have C++14 by wfunction on Tuesday August 19, 2014 @01:38PM (#8198682)
Ok, that explains it. When you're used to Java it's easy to expect inheritance to be a big deal. The fact of the matter is that run-time polymorphism (aka virtual) is much more rarely necessary in the C++ world than the Java world. The only reason it's common in Java is that it's the only tool available for many job that C++ has other tools for, and it also avoids an extra composition overhead that doesn't exist in C++.

tl;dr: Just because it's "infinitely more valuable" in Java doesn't mean the same for C++.

Re:We have C++14 by nly on Monday August 18, 2014 @07:51PM (#8195316)
It's a lot easier to reason about your first version of 'someMethod', which passes by value, than the second. It can actually be more performant than the second as well, since the code inside the body of the function (which may have been compiled during another invocation of the compiler on a seperate file) now knows the dynamic type of the object it's dealing with, meaning all interior virtual calls can be made direct.

The first form of 'someMethod' will also accept all 4 combinations of moves and copy operations on 'SomeClass': (copy a, copy b), (copy a, move b), (move a, copy b), (move a, move b). Your second, less convenient, function results in moves degrading to copies, leaving performance on the table if 'someMethod' performs mutation.

Your 'y = f(x)' ambiguity isn't a problem in practice, since most code styles use different naming conventions for classes/structs and function names.

Conversions, construction, copy, move, and assignment semantics etc, are one of the most important, and one of the most difficult things to get right, when it comes to class design. If you make sane choices though, and put thought in to it, automatic conversions etc shouldn't be bothersome.

Re:We have C++14 by maxlybbert on Monday August 18, 2014 @11:07PM (#8195886)
I find it amazing that people seem to believe it should be possible to understand a large code base by looking at single lines in isolation.
Re:We have C++14 by SamReidHughes on Monday August 18, 2014 @04:11PM (#8194381)
> In languages like C++ "verbose" means "specific and obvious"

Whoa, no it doesn't. C++ is far more verbose than necessary for things like creating algebraic datatypes or really creating any types.

Re:We have C++14 by jjoonathan on Monday August 18, 2014 @04:46PM (#8194579)
Or looping through for loops. I remember the jaw-hitting-floor moment when my C++ book tried to pass off

    std::vector<int>::iterator it;
    for (it=arr.begin(); it!=arr.end(); it++) {
        ...
    }
as an improvement over

    for (int i=0; i<len; i++) {
        ...
    }
Not entirely unrelated: I'm currently busy verbosifying a large chunk of C++11 code into C++90 code because Reasons (or so the maintainers assure me).
Re:We have C++14 by azoth_ on Monday August 18, 2014 @05:37PM (#8194854)
In modern C++ these loops could alternatively be written as:

  std::vector<int> myVec;
  for( auto it = myVec.begin(); it != myVec.end(); ++it );
or if you prefer the external begin/end syntax:

  for( auto it = std::begin(myVec); it != std::end(myVec); ++it );
or the most succinct (replace && by & if writing):

  for( auto && item : myVec );
Re:We have C++14 by pbsd on Monday August 18, 2014 @06:11PM (#8194994)
> or the most succinct (replace && by & if writing):

That is strictly not necessary. `auto&&` is what is now being called a universal reference: `item` resolves to `const int&` if `myVec` is const, and to `int&` if `myVec` is mutable. `auto&&` does the right thing in the majority of cases. In fact, the following extension [1] has been proposed for C++17 (and already implemented in recent clang builds):

    for( item : myVec ) { /* do stuff */ }
which is meant to be a short-hand for

    for( auto&& item : myVec ) { /* do stuff */ }
[1] http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n399...
Re:We have C++14 by StephanTLavavej on Monday August 18, 2014 @11:09PM (#8195888)
Both auto& and auto&& produce const T& for a const vector<T>, and T& for a modifiable vector<T>. The difference between them is subtle: auto&& handles Humanity's Eternal Nemesis, vector<bool>.
Re:We have C++14 by pbsd on Tuesday August 19, 2014 @12:33AM (#8196036)
Oops, you're right of course; I got reference collapsing rules confused with the regular binding rules. Proxy objects will only bind to auto const& or auto&&, though, since they're generally returned by value. I was surprised to see that this does not come up in std::bitset nor std::valarray, but only std::vector<bool>.
Re:We have C++14 by jjoonathan on Monday August 18, 2014 @05:56PM (#8194940)
Yes, and it's probably good to note that the issue has been fixed so as to not unduly scare away any newcomers to C++. Thanks for doing it for me :) Still, at the time the

    for(auto& item : vec)
syntax was merely a talking point being tossed around C++0x meetings. And to this day the project I'm working on still hasn't officially dropped support for C++90 so I'm stuck with the old syntax anyway :/
Re:We have C++14 by ThatOtherPerson on Monday August 18, 2014 @05:25PM (#8194782)
It's an improvement in the sense that it's more general; you can loop through any container that implements that protocol, which most (if not all) of the STL containers do. For example,

    template <class T>
    void foo(T arr)
    {
        for (auto it = arr.begin(); it != arr.end(); ++it)
        {
            std::cout << *it << std::endl;
        }
    }
You could pass a `std::map<int>` to `foo`, or a `std::list<string>`, or a `std::vector<char>`. You could even create your own classes and give them to `foo`, as long as they implement the `begin`/`end` protocol.

It's certainly more verbose than necessary, but it can be convenient.

Re:We have C++14 by nly on Monday August 18, 2014 @06:37PM (#8195093)
You want to use 'T const&' as your argument type, not 'T', otherwise foo() will take a copy of anything you pass.
Re:We have C++14 by zak_mc_kracken on Monday August 18, 2014 @08:04PM (#8195367)
I've never understood the STL's infatuation with iterators. Why do I even need to know about them when all I want is walk through the collection?

Ideally, it should be something like:

    for (auto it : arr) {
      // do something with *it
    }
Re:We have C++14 by jeorgun on Monday August 18, 2014 @08:38PM (#8195472)
You can do that. That's part of C++11 and is supported by basically every major compiler.

The advantage of iterators is that they're incredibly flexible. You can use them for sub-ranges, reversed ranges, non-ranges like input and output iterators, etc, etc. This is vastly more powerful than something like, say, Objective C's NSFastEnumeration, which just allows for the trivial case handled by the range-based for-loop.

Re:We have C++14 by mpyne on Monday August 18, 2014 @08:47PM (#8195510)
> Why do I even need to know about them when all I want is walk through the collection?

Because there are algorithms where you may not want to walk through the whole collection. STL wasn't meant to be a container library alone, it also includes many generic algorithms that work using iterators to delimit the range of data to be operated upon.

Re:We have C++14 by jonstewart on Monday August 18, 2014 @08:28PM (#8195438)
It basically is this easy these days, thankfully. It is nice to have iterators, though, because it allows you some flexibility for swapping out the underlying data structures on existing algorithmic code. This has proved quite useful when I've written graph code.
Re:We have C++14 by jjoonathan on Monday August 18, 2014 @05:53PM (#8194925)
Oh yes, and I'm hella thankful for those containers. I just wish "auto" had come along a little sooner :)
Re:We have C++14 by 72deluxe on Tuesday August 19, 2014 @04:31AM (#8196436)
I remember reading Stroustrup's book and not having a clue what an "iterator" was. Even looking in dictionaries didn't help me - I was just after the very definition of the word!

Times have changed now of course.

Re:We have C++14 by kazinator on Monday August 18, 2014 @07:06PM (#8195182)
Indeed!

Just to write a class in C++ with a constructor and destructor which are not inlined, you have to repeat the class name about seven times: three times in the class declaration. Then four more times in the definitions of those two functions:

    class verbose {
    public:
      verbose();
      ~verbose();
    };

    verbose::verbose()
    {
    }

    verbose::~verbose()
    {
    }
Re:We have C++14 by RogerL on Monday August 18, 2014 @06:25PM (#8195057)
Stroustrup doesn't think so.

I don't have a link - it was in some recent conference. He stated that every time he added a new feature everyone would be up in arms and demand a really verbose implementation, which he added reluctantly. Now that everyone is used to the features they complain about how ridiculously verbose it all is.

There isn't any reason for the craziness of

    template<typename T> 
    void foo(T a)
vs

    void foo(auto a)
Certainly things can become too implicit, but C++'s heritage of verboseness is due to the conservatism of the standards committee, not because anything less would be confusing.
Re:We have C++14 by dllthomas on Monday August 18, 2014 @07:00PM (#8195160)
But the expanded form does provide you with more flexibility. Even if the latter is a synonym for the former, there is a difference between:

    template<typename T>
    void foo(T a, T b)
vs

    void foo(auto a, auto b)
Re:We have C++14 by kazinator on Monday August 18, 2014 @07:09PM (#8195195)
It seems like in the second `foo`, the types of `a` and `b` are not hinged together. So to do it with the template syntax you actually need:

    template<typename T, typename U>
    void foo(T a, U b)
:)
Re:We have C++14 by dllthomas on Monday August 18, 2014 @08:53PM (#8195528)
I intended the two to share a type. My point was that you cannot express that constraint with only auto.
Re:We have C++14 by syncsynchalt on Monday August 18, 2014 @06:50PM (#8195137)
The reason for your particular example is path dependency — templates came long before (the redefinition of) auto.
Re:We have C++14 by spott on Monday August 18, 2014 @10:12PM (#8195726)
I was specifically referring to boilerplate and type level programming: Algebraic Data Types's, and type generation in general.

C++'s type system is actually pretty strong, but the amount of boilerplate that is needed to create a new type means that it is very difficult to program in a type safe way... without being incredibly verbose. Creating a type safe "Length" type is too much of a pain in the ass for anyone to actually do it.

Which is what I mean by "too verbose". It is so verbose that instead of securing the "specific and obvious" in strong compiler guarantees, we fake it with implicit conversions and typedefs.