News for hackers. Stuff that matters.
Re:Bjarne Stroustrup – The Essence of C++ [video] by Aldo_MX on Tuesday September 17, 2013 @06:06AM (#6398426)
I liked this snippet about pointer misuse:

  void f(int n, int x)
  {
    Gadget* p = new Gadget(n);  // look I'm a java programmer! :)
    // ...
    if(x<100) throw std::runtime_error("Weird!");  // leak
    if(x<200) return;                              // leak
    // ...
    delete p;  // and I want my garbage collector! :(
  }
Re:Bjarne Stroustrup – The Essence of C++ [video] by harrytuttle on Tuesday September 17, 2013 @06:29AM (#6398487)
I rather prefer Java:

    void f(int n, int x) {
        Gadget p = new Gadget(n);
        // ...
        if (x < 100) throw new Exception("Weird!); // no leak
        if (x < 200) return;
        // ...
    }
Yes, good night's sleep tonight after writing that...
Re:Bjarne Stroustrup – The Essence of C++ [video] by fhd2 on Tuesday September 17, 2013 @06:35AM (#6398507)
The point of the example is that this is how NOT to do it in C++.

There are two better options:

  void f(int n, int x) {
      Gadget p(n); // Stack allocated
      // ...
      if (x < 100) throw new Exception("Weird!); // no leak
      if (x < 200) return;
      // ...
  }
Or, if it really has to be a pointer:

  void f(int n, int x) {
      std::unique_ptr<Gadget> p = new Gadget(n); // Smart pointer
      // ...
      if (x < 100) throw new Exception("Weird!); // no leak
      if (x < 200) return;
      // ...
  }
Both will be automatically freed as soon as the scope is exited.
Re:Bjarne Stroustrup – The Essence of C++ [video] by harrytuttle on Tuesday September 17, 2013 @06:42AM (#6398533)
What I was hoping you'd say :)

This is fine until I want to do this, at which point C++ becomes a memory management bastard:

    void f(int n, int x) {
        Gadget g = new Gadget(n);
        // ...
        if (x < 100) throw new GadgetException("Gadget broke", x);
        if (x < 200) return;
        // ...
    }
Re:Bjarne Stroustrup – The Essence of C++ [video] by skrebbel on Tuesday September 17, 2013 @07:18AM (#6398619)

    Gadget g = new Gadget(n);
That code won't compile unless Gadget has an assignment operator that accepts a pointer, which is, well, not a very common scenario.

Note: I'm not trying to be nitpicky. I really don't understand what you mean when you write that you "want to do this".

Now, I don't know anything about you, but based off your comments in this thread I'm not sure you have a working knowledge of C++.

Re:Bjarne Stroustrup – The Essence of C++ [video] by kybernetyk on Tuesday September 17, 2013 @06:47AM (#6398549)
you can always fake a defer:

    void f(int n, int x) {
      Gadget g = new Gadget(n);
      std::shared_ptr<void> defer(nullptr, [g](void *) {
        delete g;
      });
    ...
But honestly ... I'd just use a stack allocated object - or a smart pointer. In the last year I didn't write one delete. (I'm a full time C++ dev).
Re:Bjarne Stroustrup – The Essence of C++ [video] by fhd2 on Tuesday September 17, 2013 @07:24AM (#6398637)
Well, what's easy in Java here is that you're effectively always working with shared objects. That's easy to use, but in my experience quite error prone, I can't count how many memory leaks I fixed in Java/JS code. YMMV.

In C++, you have various ways of referencing and passing objects, so you need to be aware of the lifetime and ownership of objects. It's arguably harder, and unfortunately, the C heritage makes it a lot harder than it needs to be :(

Re:Bjarne Stroustrup – The Essence of C++ [video] by detrino on Tuesday September 17, 2013 @10:30AM (#6399476)
This code makes no sense. I think you do not understand C++ very well.
Re:Bjarne Stroustrup – The Essence of C++ [video] by easytiger on Tuesday September 17, 2013 @07:48AM (#6398698)
isn't that illegal?
Re:Bjarne Stroustrup – The Essence of C++ [video] by Sharlin on Tuesday September 17, 2013 @06:36AM (#6398509)
Java:

    void f(int n, int x) {
        Reader fr = new FileReader("foo.txt");
        // ...
        if (x < 100) throw new Exception("Weird!); // resource leak
        if (x < 200) return;                       // resource leak
        // ...
    }
A garbage collector that gives a false sense of security is much worse than no garbage collector at all.
Re:Bjarne Stroustrup – The Essence of C++ [video] by harrytuttle on Tuesday September 17, 2013 @06:43AM (#6398537)
try/finally in Java / using in C# are designed for that scenario.
Re:Bjarne Stroustrup – The Essence of C++ [video] by Sharlin on Tuesday September 17, 2013 @09:20AM (#6399080)
And try/finally assigns the cleanup responsibility to the caller, not the callee, which just adds boilerplate and mental burden. C++ does not need a finally block due to RAII. The using block (and "try-with-resource" in Java 7) is a poor man's RAII emulation.

Anyway, what if you need to share non-memory resources? Suddenly you cannot depend on the garbage collector, you cannot use try/finally, you cannot use using or try-with-resource - you need to handle the situation just like in C++, except you're given fewer tools to do it - and a poorer understanding of the situation if you've learned that you don't need to do manual resource management due to the garbage collector.

Re:Bjarne Stroustrup – The Essence of C++ [video] by pkolaczk on Tuesday September 17, 2013 @10:13AM (#6399368)
True, but 90% of resources is memory. Java makes 90% of resources much easier to handle and 10% only little harder (like always use the try-catch-finally or try-with-resources).
Re:Bjarne Stroustrup – The Essence of C++ [video] by detrino on Tuesday September 17, 2013 @10:50AM (#6399615)
They are poor solutions compared to RAII: leaky abstractions which are non-composable and error prone. Unfortunately, something like C# using is probably the best you can do in a language without clear ownership semantics like C++.
Re:Bjarne Stroustrup – The Essence of C++ [video] by pyrtsa on Tuesday September 17, 2013 @07:28AM (#6398653)
But you'll need to document it very visibly that "Thou shalt call resource.close() whatever happened."

C++ makes it possible for the library writer to take care of freeing the resources automatically.

Re:Bjarne Stroustrup – The Essence of C++ [video] by moron4hire on Tuesday September 17, 2013 @08:55AM (#6398948)
A class implementing IDisposable is that documentation. You shouldn't need more documentation than the fact that IDisposable is there.
Re:Bjarne Stroustrup – The Essence of C++ [video] by jasomill on Tuesday September 17, 2013 @10:33PM (#6403086)
An annoying fly in this ointment is cases where objects assume the responsibility for calling Dispose on caller-provided disposable objects. While it should always be okay to "double-dispose", this is only a guideline, and can't be enforced by the language, so, to maximize future compatibility with classes outside your control, you should probably defensively avoid calling Dispose on an object that will have already been disposed by other means.
Re:Bjarne Stroustrup – The Essence of C++ [video] by vertex-four on Tuesday September 17, 2013 @09:27AM (#6399105)
Go's defer keyword is good for this. You could also attach a finalizer to the struct, to panic/log in case it's never closed.
Re:Bjarne Stroustrup – The Essence of C++ [video] by sgoody on Tuesday September 17, 2013 @08:42AM (#6398896)
I'm a C# dev and I totally agree with this.

I've done a limited amount of C++ many many years ago before I even knew what garbage collection was and I keep thinking of revisiting it, but honestly in my line of work ("Enterprise") I don't need the mental overhead of dealing with things such as pointers and memory allocation.

Perhaps, my view is outdated, but I get the impression that everything in C/C++ is just a little thorny when compared to other slightly more high-level languages, such as namespaces, package management, list comprehensions, library compatibilities, type strictness etc.

I would like to be wrong about that though... I wish I had a little more motivation to spend some real time with C++ (or perhaps even C).

Re:Bjarne Stroustrup – The Essence of C++ [video] by tspiteri on Tuesday September 17, 2013 @06:35AM (#6398508)
The point is not about C++ vs Java, it is rather about writing C++ like you would write Java, which leads to leaks.
Re:Bjarne Stroustrup – The Essence of C++ [video] by abrahamsen on Tuesday September 17, 2013 @08:29AM (#6398857)
Yes, Java is a far superior language than C++ for writing Java code.
Re:Bjarne Stroustrup – The Essence of C++ [video] by harrytuttle on Tuesday September 17, 2013 @08:42AM (#6398894)
My point entirely :)
Re:Bjarne Stroustrup – The Essence of C++ [video] by pyrtsa on Tuesday September 17, 2013 @07:22AM (#6398632)
Nitpick:

    if (x < 100) throw new Exception("Weird!); // LEAK!
You shouldn't use `new` either when throwing exceptions. Just:

    if (x < 100) throw Exception("Weird!); // no leak.
Re:Bjarne Stroustrup – The Essence of C++ [video] by Sharlin on Tuesday September 17, 2013 @09:24AM (#6399094)
The grandparent's code is Java, not C++.
Re:Bjarne Stroustrup – The Essence of C++ [video] by userulluipeste on Tuesday September 17, 2013 @06:39AM (#6398519)
In OOP its recommended to use pointers as class members, managed by class methods. What you show is a "wild" allocation that doesn't really belong to no one and thus not really managed. You're right, pointers can be misused, but what can't be? Think of infinite loops or some similar very bad algorithm choice if nothing else. No amount of language design will fix bad programming.
Re:Bjarne Stroustrup – The Essence of C++ [video] by pyrtsa on Tuesday September 17, 2013 @07:20AM (#6398623)
Bjarne's advice also applies to pointers wrapped as class members. There are just too many ways you can mess things up inside the class when dealing with raw pointers, examples including:

- partial construction: having to deal with already allocated pointers in case of errors during the construction - copy construction: who owns the resources? (Alternatively, you'll need to remember to disable the copy constructor explicitly.) - copy assignment: likewise

Doing the Right Thing is just so much easier when you wrap those member objects into e.g. `std::unique_ptr<T>`. That'll disable copy construction and assignment, which means that you'll need to think of that separately if it's needed.

Re:Bjarne Stroustrup – The Essence of C++ [video] by userulluipeste on Tuesday September 17, 2013 @07:47AM (#6398696)
These are problems that pop out from a bad design choices. One of the first things I remember from OOP learning is that constructors should be as safe as they can be, which means no allocations, partial or not. Of course it is tempting to misuse the language features out of personal commodity and blame someone else. I think we can agree that a few design changes would solve the ambiguous cases. Also, for the "remembering" problem, we can inherit from a base class having all the needed restrictions in place. The std's "something_ptr" gimmicks may sound like a good compromise at first, but just like the garbage collector, these will make you lazy and neglectful over time. It's good for those to exist though.
Re:Bjarne Stroustrup – The Essence of C++ [video] by daxelrod on Tuesday September 17, 2013 @09:00AM (#6398975)
> constructors should be as safe as they can be, which means no allocations, partial or not.

Can you expand upon what you mean by "safe" here?

If you mean "unable to fail", I vehemently disagree. Constructors should validate what is passed into them and fail if that is invalid. The alternative is to construct a zombie object that can't actually be used. Objects like this subvert the type system and lead to lots of unnecessary "if object.is_valid()" checks all over code that uses them.

Re:Bjarne Stroustrup – The Essence of C++ [video] by userulluipeste on Wednesday September 18, 2013 @06:58AM (#6404539)
"safe" like nullifying pointers and dummy-initialization for objects. This kind of initialization has a small footprint on performance, but it was made optional nevertheless, due to language's performance aims (you can skip them if you don't need that). You can make a little bit more complex operations in constructors that involve data validation, but it should only default to blank initialization if something doesn't pass the checks. The initialization that can fail (and the failure must be taken in account) should be done outside constructors. If an object is or isn't considered valid after a dummy initialization is a design decision, and likewise an adjustment in design can avoid excessive "if (object.is_valid())" kind of checks.
Re:Bjarne Stroustrup – The Essence of C++ [video] by AnthonyMouse on Tuesday September 17, 2013 @08:02AM (#6398740)
>That'll disable copy construction and assignment, which means that you'll need to think of that separately if it's needed.

If you have a pointer in a class that is exactly what you want to happen in most cases. Then if you want copies you "have to" define your own copy constructor and assignment operator that copy the object pointed to rather than just copying the pointer.

Re:Bjarne Stroustrup – The Essence of C++ [video] by curyous on Tuesday September 17, 2013 @06:56AM (#6398568)
I don't think OOP means what you think it means. There's nothing in Object Oriented Programming paradigms that specifies what you should declare class members as. There are more important components to that decision such as what language you're using.
Re:Bjarne Stroustrup – The Essence of C++ [video] by userulluipeste on Tuesday September 17, 2013 @07:16AM (#6398614)
OOP means you design your thing as objects, with each object taking care of its own stuff. You don't have to use pointers, you may just use other objects as members, as you do in many other languages. Pointers just give you additional power and flexibility and if they are used in a object oriented design, its safe to assume that they should be managed by the owner object, like any other object's internal stuff.

Of course, you may prove me wrong.