News for hackers. Stuff that matters.
Re:C++ the Good Parts (2014) by derriz on Thursday October 01, 2020 @03:47AM (#24648456)
It's pretty arguable to claim that C++ is the only language with RAII.

C# has "using", Java has try-with-resources, Python has the "with", etc. - all of which support RAII patterns.

Re:C++ the Good Parts (2014) by quietbritishjim on Thursday October 01, 2020 @03:52AM (#24648482)
Those are extremely limited in comparison. For example, in C++ you can return a locked mutex-locker from a function:

    std::unique_lock<std::mutex> foo();
The unlocking of the mutex is then tied up with what you do with the returned mutex locker e.g. if you ignore it then it will be unlocked at the end of the current statement, if you assign it to a local variable (and don't move from that) then it will be destroyed when leaving that enclosing function, or you return it from that enclosing function to extend the length of the lock still further.

You also can't compose those mechanisms so easily. For example I could make a class with a std::unique_lock<std::mutex> and a pointer to the data it protects and pass that around.

Re:C++ the Good Parts (2014) by chronial on Thursday October 01, 2020 @04:48AM (#24648830)
At least for python, using is not more limited, but more complete: It allows to handle exceptions that are raised in the block and it also allows you to raise exceptions in the "destructor".

That is something that you actually need rather frequently. For example a db transaction wrapper might want to rollback instead of commit if we leave the block via an exception. You also want the "destructor" of that block to raise if the transaction can't be committed.

The only thing that the c++ method does really well is memory management (e.g. unique_ptr), because free() can't fail. But that use case is of course not a thing in gc languages.

Regarding the composition: Everything that's not memory management usually has side-effects and often wants to do something with regards to exceptions. So it's a good thing for the caller to know that the "RAII" is happening. Allowing you to complete hide that in your class is not a benefit.

C++ paints a distorted picture here, because its method is great for memory handling issues, but only OKish for everything else. But most of your RAII issues in C++ are memory related, so you don't notice the problems that much.

Re:C++ the Good Parts (2014) by jcelerier on Thursday October 01, 2020 @06:32AM (#24649371)
> At least for python, using is not more limited, but more complete: It allows to handle exceptions that are raised in the block and it also allows you to raise exceptions in the "destructor".

the difference is that with Python, the programmer can forget to use "using". In C++, as soon as you instantiate your variable on the stack somewhere, you know that ~T() will happen unless you get a segfault...

> For example a db transaction wrapper might want to rollback instead of commit if we leave the block via an exception.

I'd say that a transaction wrapper would have an explicit commit method which applies the transaction and "empties" the transactoin object - destructor would always rollback if there is something that was not committed - and if commit was called then there is nothing to rollback anymore so ~T() does nothing.

Re:C++ the Good Parts (2014) by geofft on Thursday October 01, 2020 @01:02PM (#24653380)
The way you'd do this in Python is something like

    @contextlib.contextmanager
    def get_a_locked_thing():
        with lock:
            yield thing
and then

    with get_a_locked_thing() as thing:
        do_stuff_with(thing)
Exiting this "with" block causes get_a_locked_thing to resume at its yield statement, which exits that "with" block, which releases the lock. Throwing an exception also exits the context managers.

If you were to try omitting the "with" statement and running, say, "thing = get_a_locked_thing()", the function hasn't executed yet (because you haven't entered the context manager), meaning that not only is 'thing' the wrong object, you also haven't even gotten the lock yet. So you won't deadlock/leak the lock, and you will notice in the most basic of tests that your code isn't doing the right thing.

I do agree that this is nowhere near as nice as having an object in a local variable, because "with" adds an extra layer of indentation, and that's an advantage of C++/D/Rust-style RAII. But it's definitely doable in Python and pretty idiomatic.

Re:C++ the Good Parts (2014) by quietbritishjim on Thursday October 01, 2020 @05:31PM (#24656341)
Ah good point, that is perfectly doable. But even accepting the explicit with statements, it's still not as composable in more general situations. For example, I don't see how to reliably pass an active context manager to a function for it to unlock part way through its execution, or return one of two active context managers (if you tried using your technique then both would still be active if you couldn't exit the undesired one before the yield). But maybe you're right that these are a bit less common, except for memory management, than I'm imagining.
Re:C++ the Good Parts (2014) by quietbritishjim on Thursday October 01, 2020 @07:18AM (#24649615)
The one example I gave in the parent comment already addresses everything you talked about.

Yes you can use a Python context manager (that's what you're referring to) to lock a mutex, but you can't pass that context manager as a return result of a function and be sure its __exit__ method will be called appropriately in the three situations I mentioned (immediately if result thrown away, at the end of the function if stored in a local variable, later still if returned from that outer function).

In fact I don't think you can return a context manager from within a "with" block at all, even accepting that the parent function will have to manually reuse it in another with block, because its __exit__ method will already be called in the inner function. Technically this is true in C++ too of course because the object in the inner function will have its destructor called, but its move constructor will be called first giving you an opportunity to clear out its internal state (this is why my example used a unique_lock rather than a lock_guard). Things are even better in Rust: the bytes of the object are directly copied to the new object's footprint and the original destructor isn't called, so you don't even need to set up a dummy "empty" state.

> The only thing that the c++ method does really well is memory management (e.g. unique_ptr), because free() can't fail.

Mutex unlocking usually can't fail (and if they do, there's usually not much you can do about it). Same with closing network connections. Closing files can fail, and for some programs it's very important to know when that happens, but for many others it's not important at all. Python's chained exceptions are very nice, but not so important that their absence from C++'s exceptions (or Rust's panics) makes those languages useless.

Re:C++ the Good Parts (2014) by gpderetta on Thursday October 01, 2020 @10:09AM (#24650951)
RAII is great for transactions. In a proper robust design, commits should always be explicit and destructors only rollback uncommitted transactions. If your rollback can fail, well, then you have bigger issues.

There is now enough introspection in the language to actually implement implicit commit in a non exceptional path, but I think it would be a mistake.

Re:C++ the Good Parts (2014) by secondcoming on Thursday October 01, 2020 @07:24AM (#24649649)
> For example I could make a class with a std::unique_lock<std::mutex> and a pointer to the data it protects and pass that around.

This is pretty much what we do in our code base, except that the class has lock(), tryLock(), etc functions that take a lambda. The functions acquire/try to acquire the mutex and then pass a reference with appropriate const-ness to the lambda.

Re:C++ the Good Parts (2014) by pjmlp on Thursday October 01, 2020 @04:52AM (#24648861)
So let me make it boom in C++,

    auto my_leaky_mutex = new std::unique_lock<std::mutex> {foo()};
Yes, I am making it fail on purpose, but copy-paste in enterprise codebases does wonders for code quality.
Re:C++ the Good Parts (2014) by eMSF on Thursday October 01, 2020 @05:48AM (#24649151)
You're reaching. I'm not sure it adds much to parent's point.
Re:C++ the Good Parts (2014) by UncleMeat on Thursday October 01, 2020 @09:23AM (#24650523)
Using "new" is code smell. This is easily caught in code review.
Re:C++ the Good Parts (2014) by pjmlp on Thursday October 01, 2020 @10:59AM (#24651610)
Like those that Google does for Android?
Re:C++ the Good Parts (2014) by CyberDildonics on Thursday October 01, 2020 @12:40PM (#24653076)
Raw pointers for ownership are a bad idea, one of google's 30,000 programmers doing it doesn't change that. You are the only one pointing to google as an authority.
Re:C++ the Good Parts (2014) by pjmlp on Friday October 02, 2020 @10:49AM (#24663185)
I am the only one, because the others don't care to point anything.
Re:C++ the Good Parts (2014) by CyberDildonics on Friday October 02, 2020 @12:26PM (#24664236)
Other people are pointing to the actual fundamental reasons these things exist and are valuable, you are pointing to a bizarre false authority as a desperate rationalization for not liking C++.
Re:C++ the Good Parts (2014) by UncleMeat on Thursday October 01, 2020 @02:17PM (#24654323)
You are really harping on this one example.

I don't know what processes Google uses for the Android codebase, but in the main code base make_shared has only been available for a little while. Today, "new" is smell that should be caught in code review at Google. When was this committed?

Re:C++ the Good Parts (2014) by pjmlp on Friday October 02, 2020 @10:53AM (#24663242)
Yes, because Google is a major contributor to ISO C++, LLVM, clang, has billions of C++ code, and yet fails to follow best practices.

So what to be expected by those companies that hardly have such a deep knowledge about C++ among their troops?

Re:C++ the Good Parts (2014) by pkolaczk on Friday October 02, 2020 @02:38PM (#24665629)
Google is a huge company and the majority of its employees are not contributors to ISO C++.
Re:C++ the Good Parts (2014) by masklinn on Thursday October 01, 2020 @07:49AM (#24649836)
All the construct you’re mentioning are nice and useful but they are solely lexical, this means unlike RAII you can’t protect every use of the resource, if you need to return or pass along sais resource they will not work for instance.

RAII is strictly more powerful and more regular than context managers.

Re:C++ the Good Parts (2014) by gpderetta on Thursday October 01, 2020 @07:16AM (#24649601)
They are still different: 'using', 'with' are tied to scope, RAII is tied to lifetimes which in turn can be tied to scope but do not have to. It also applies to every object and subobject transitively and implicitly, without having to implement some special protocol [1].

[1] if you are implementing something like a container and dealing to raw memory you might need to call destructors of subobjects explicitly, but because it is needed to correctly reclaim memory, it is almost always done and all standard containers do it already. On the other hand in python list doesn't implement the context manager protocol.

Re:C++ the Good Parts (2014) by 72deluxe on Thursday October 01, 2020 @04:00AM (#24648544)
This is true. But C++'s destructor behaviour means you get this pattern without any thought, and consistently and reliably and deterministically, whereas other types eg. C#'s "using" statement requires explicit usage, which isn't as convenient at all.
Re:C++ the Good Parts (2014) by pjmlp on Thursday October 01, 2020 @04:17AM (#24648654)
Only if the objects aren't heap allocated via new/delete, and you happen to forget to call delete on it.
Re:C++ the Good Parts (2014) by platinumrad on Thursday October 01, 2020 @06:38AM (#24649396)
`new` and `delete` have been banned outside of deep library code in every industrial C++ codebase I've ever worked on.
Re:C++ the Good Parts (2014) by todd8 on Friday October 02, 2020 @03:09AM (#24659846)
I don’t have first hand experience in the world of game programming, but I’ve heard that smart pointers aren’t used and old fashioned new and delete are standard practice. (Please correct me if I’m wrong, I’m curious if what I’ve heard about game development is really true.)
Re:C++ the Good Parts (2014) by pjmlp on Thursday October 01, 2020 @07:33AM (#24649707)
Re:C++ the Good Parts (2014) by darkmx0z on Thursday October 01, 2020 @09:11AM (#24650427)
did you check the header of that cpp? they are storing it in a shared_ptr: shared_ptr = referenced counted pointer = RAII

they should have used make_shared, but it is still safe

Re:C++ the Good Parts (2014) by pjmlp on Friday October 02, 2020 @01:56AM (#24659369)
Which isn't exception safe, as any good C++ developer would know.
Re:C++ the Good Parts (2014) by msla on Thursday October 01, 2020 @03:40PM (#24655337)
"Google Does Bad Thing" is not quite equivalent to "C++ Is Bad Language"
Re:C++ the Good Parts (2014) by pjmlp on Friday October 02, 2020 @01:59AM (#24659379)
Indeed, it is even one of my favourite languages, but contradicts the OP's point of every industry C++ codebase has banned new and delete.
Re:C++ the Good Parts (2014) by int_19h on Thursday October 01, 2020 @06:18PM (#24656752)
The Google C++ style guide alone is sufficient evidence to conclude that Google doesn't know how to do C++ properly.
Re:C++ the Good Parts (2014) by pjmlp on Friday October 02, 2020 @04:48AM (#24660517)
Yet they are one of the major contributors to ISO C++ and LLVM, what gives?
Re:C++ the Good Parts (2014) by int_19h on Friday October 02, 2020 @09:55PM (#24668862)
It just means that they still derive value from C++. But I, for one, am very glad that they're not a dominant force in the ISO standard committee.
Re:C++ the Good Parts (2014) by ncmncm on Saturday October 03, 2020 @02:21AM (#24670015)
In a word, not.
Re:C++ the Good Parts (2014) by secondcoming on Thursday October 01, 2020 @07:08AM (#24649569)
Well yes, C++'s destructor behaviour doesn't work if you don't use C++...
Re:C++ the Good Parts (2014) by cgrealy on Thursday October 01, 2020 @08:24AM (#24650072)
That's not really fair.

  Thing* thing = new Thing();
  thing->DoStuff();
  delete thing;
is perfectly valid C++ and has been since the invention of the language. It's not a good idea, but it is valid.

If, OTOH, you do

  Thing* thing=(Thing*)malloc(sizeof(Thing));
  free(thing);
the you fully deserve the inevitable world of pain that is coming your way
Re:C++ the Good Parts (2014) by jcelerier on Thursday October 01, 2020 @10:59AM (#24651609)
> is perfectly valid C++

we're in 2020.

    $ clang-tidy -checks='cppcoreguidelines-*' foo.cpp 
    /tmp/foo.cpp:10:3: warning: initializing non-owner 'Thing *' with a newly created 'gsl::owner<>' [cppcoreguidelines-owning-memory]
      Thing* thing = new Thing();
      ^
    /tmp/foo.cpp:12:3: warning: deleting a pointer through a type that is not marked 'gsl::owner<>'; consider using a smart pointer instead [cppcoreguidelines-owning-memory]
      delete thing;
      ^
    /tmp/foo.cpp:10:3: note: variable declared here
      Thing* thing = new Thing();
      ^
Re:C++ the Good Parts (2014) by cgrealy on Thursday October 01, 2020 @03:46PM (#24655416)
Does it compile? Does it run? Yes, therefore it's valid C++.

I'm not arguing it's good C++, but saying "C++'s destructor behaviour doesn't work if you don't use C++" in relation to using new and delete is clearly nonsense.

Re:C++ the Good Parts (2014) by umanwizard on Tuesday October 06, 2020 @08:40PM (#24704141)
The malloc/free version is perfectly valid C++ too, isn’t it?
Re:C++ the Good Parts (2014) by cgrealy on Tuesday October 13, 2020 @10:32PM (#24772550)
Eh... kind of?

I guess it depends on your definition of "valid".

Let's say we have:

  class Thing
  {
  public:
    Thing() { cout << "created" << endl; }
    ~Thing() { cout << "destroyed" << endl; }
  };
Assuming the happy path, the new/delete version will be functionally identical to a more correct/idiomatic

  {
    auto thing = make_unique<Thing>();
  }
The malloc/free version won't call the destructor, and therefore doesn't do what a "normal" object would do.

It's splitting hairs, I guess, but that's where I'd draw the line.

Re:C++ the Good Parts (2014) by pjmlp on Thursday October 01, 2020 @07:11AM (#24649584)
Which is what plenty of people do across the industry with C++ compilers, they code like C.
Re:C++ the Good Parts (2014) by secondcoming on Thursday October 01, 2020 @08:04AM (#24649926)
Well that's not C++'s fault. Those people are either stuck on a particular compiler version, are in a maintenance mode, or are just unwilling to improve themselves. Maybe there's job security in being able to write code in a deprecated style.
Re:C++ the Good Parts (2014) by badsectoracula on Thursday October 01, 2020 @01:29PM (#24653744)
> or are just unwilling to improve themselves

Or they may not see that stuff as an improvement in the first place (e.g. see Orthodox C++[0]).

[0] https://gist.github.com/bkaradzic/2e39896bc7d8c34e042b

Re:C++ the Good Parts (2014) by Jtsummers on Thursday October 01, 2020 @03:45PM (#24655403)
If I'm reading that right, they start off talking about a minimalist/reduced subset of C++, and then end up concluding: Use C++14 (now two standards ago) and we'll probably recommend C++17 in 2022 (5 year delay).

That seems like a rather weak conclusion given all the words that preceded it. You might as well just start and end with this:

New standards have issues, people don't know how to use them correctly, and compilers are slow to catch up. Wait 5 years to use a standard so all these things are worked out, and you don't have to worry about the details that don't stick.

Re:C++ the Good Parts (2014) by badsectoracula on Friday October 02, 2020 @07:35AM (#24661534)
The C++14 part seem to be added lately and indeed sounds contradictory to what was written previously. As a comment below writes though they use the original Orthodox C++ idea without the C++14 part (and TBH i think the whole "committee" part is a tongue-in-cheek joke).

In any case this is just an example, there are a couple of similar "subsets" with the same idea of keeping C++ use to its bare minimum, it is just that i remember this one because of the name :-P

Re:C++ the Good Parts (2014) by hyperpl on Thursday October 01, 2020 @03:18PM (#24655111)
Wow, I thought I was alone.
Re:C++ the Good Parts (2014) by ncmncm on Friday October 02, 2020 @05:53PM (#24667396)
It is always the right time to learn modern C++.

Discomfort is not a valid reason to avoid learning new things.

Re:C++ the Good Parts (2014) by unishark on Thursday October 01, 2020 @08:47AM (#24650237)
Historically there was a big performance hit for using the fancy added abstractions of C++. Don't know if it's still that bad. But in the past it cost a factor of two or so, whenever I tried to get fancy.
Re:C++ the Good Parts (2014) by jcelerier on Thursday October 01, 2020 @11:01AM (#24651649)
> Historically there was a big performance hit for using the fancy added abstractions of C++. Don't know if it's still that bad. But in the past it cost a factor of two or so, whenever I tried to get fancy.

I don't know how much back in the past it is, but pretty much every time in the last ten years I tried to beat a C++ abstraction, I almost never managed to substantially improve (and since gcc.godbolt.org exists it made it much easier to witness that most of the abstraction layers entirely disappear at -O2)

Re:C++ the Good Parts (2014) by ncmncm on Friday October 02, 2020 @08:33PM (#24668443)
Historically, meaning "in the '90s". It has been quite a long time since the '90s. Many readers here weren't even born yet when C++ abstraction overhead was last a thing.
Re:C++ the Good Parts (2014) by pjmlp on Thursday October 01, 2020 @08:27AM (#24650091)
Like Android NDK?
Re:C++ the Good Parts (2014) by secondcoming on Thursday October 01, 2020 @12:34PM (#24652974)
No idea, I've no experience with it.
Re:C++ the Good Parts (2014) by pjmlp on Friday October 02, 2020 @02:03AM (#24659405)
You should, then you will see how much C++ it actually uses.

It exposes everything as C APIs, even thought it is a mix of Java and C++ on the implementation side, leaving the C++ developers to write their own type safe abstractions from scratch.

Most just can't be bothered and write C in C++.

Then there is the whole issue how, following Google C++'s guidelines, the NDK is actually implemented.

Re:C++ the Good Parts (2014) by steerablesafe on Thursday October 01, 2020 @04:44AM (#24648801)
smart pointers exist
Re:C++ the Good Parts (2014) by pjmlp on Thursday October 01, 2020 @04:53AM (#24648870)
Just like value types and deterministic resource management in GC languages.
Re:C++ the Good Parts (2014) by noctune on Thursday October 01, 2020 @03:57AM (#24648524)
`using` composes badly. It won't work with eg. a list of Disposables or Linq.
Re:C++ the Good Parts (2014) by ben509 on Thursday October 01, 2020 @07:36AM (#24649742)
This is the strongest argument against claiming "using" or Python's context managers are RAII.

RAII naturally composes because a container has to clean up its memory, and it has a well defined lifetime.

Python has a very straightforward model for its context managers, two magic methods:

    def __enter__(self):
        ...

    def __exit__(self, etype, eval, tb):
        ...
To handle many resources being released, the stdlib prefers a more direct approach using a special class:

    with ExitStack() as stack:
        files = [stack.enter_context(open(fname)) for fname in filenames]
And it makes sense. You probably don't want regular containers to have yet another magic method defined on them, and there is no clear single behavior the a container's __enter__ and __exit__ method could have.

And it doesn't compose in other ways. In async code, for instance, there's a completely separate mechanism with `async with` that calls __aenter__ and __aexit__.

It really comes down to the fact that when objects have an ambiguous lifetime, which is a consequence of garbage collection, you can't have RAII.