r/programming • • Feb 18 '20

C++20 is here!

https://youtu.be/AvPiGstxV_g
89 Upvotes

122 comments sorted by

View all comments

Show parent comments

3

u/D_0b Feb 19 '20

can you give a quick example, where the C++ checker would fail?

2

u/dreugeworst Feb 19 '20

I'm not 100% on this, but I don't think it generally tracks lifetimes across function calls, so it wouldn't complain about the following, which isn't possible in safe rust:

void blackbox(int* a)
{
    delete a;
}

void test()
{
    auto intptr = std::make_unique<int>(42);
    blackbox(intptr.get());
    std::cout << *intptr << std::endl;
}

1

u/D_0b Feb 19 '20 edited Feb 19 '20

so it is not a fair comparison, I was saying, what can safe Rust's checker handle that C++ lifetime checker can't.

or were you saying that C++ lifetime checker is not as good because it allows stuff that Rust's safe subset does not.

2

u/dreugeworst Feb 19 '20 edited Feb 19 '20

or were you saying that C++ lifetime checker is not as good because it allows stuff that Rust's safe subset does not.

You asked for situations where the rust lifetime checker would save you, and the c++ one would not. This is such a situation. You would need to drop to unsafe rust to do this, the borrow checker wouldn't allow it otherwise. I don't see why this comparison would not be fair.

If you need a different example, imagine a map where the values are structs containing a pointer / reference to a string. You pass a reference to the map to various functions to fill it, then use the values. In safe rust, the borrow checker would make sure the references don't outlive the strings they point to. In the c++ checker, this would not happen if the strings aren't owned in the same function as the map is being filled (say you have a helper function to add an entry to the map)

1

u/D_0b Feb 19 '20

OK, that was the kind of example I was looking for.