73 points · by ingve · 3y ago · 81 comments
if (foo(p.release()) == 0) { ... }
you generally need to do if (foo(p.get()) == 0) { p.release(); ... }
Instead of reducing bugs, these might be introducing new footguns. void c_api_that_returns_via_an_out_parameter(T** ret) {
*ret = new T();
}
T* p;
c_api_that_returns_via_an_out_parameter(&p);
Then you might try to change this to use a smart pointer as: std::unique_ptr<T> p;
c_api_that_returns_via_an_out_parameter(&p);
But this won't compile because you can't take the address of a `std::unique_ptr<T>` and then pass it where a `T**` is expected. So instead you need to do something like this: T* tmp = 0;
c_api_that_returns_via_an_out_parameter(&tmp);
std::unique_ptr<T> p(tmp);
That can be a bit of a pain. These new functions serve as adapters to make this easier. They take in a `std::unique_ptr<T>` and provide a `T*` that you can pass to the C API: std::unique_ptr<T> p;
c_api_that_returns_via_an_out_parameter(std::out_ptr(p));
No temporary needed.If your C API only ever passes and returns `T*` and never uses `T**` then I think that you don't need these new functions and you can continue to do things the current way. For instance, if you have a C API that allocates a new object and then returns a pointer to it then you can take this return value and immediately store it into your smart pointer:
std::unique_ptr<T> p(c_api_that_returns_a_pointer());
And if you have a C API that takes a `T**` and then deallocates it: c_api_that_deallocates(p.release());
Although really your smart pointer should be doing this for you so you'd never need to do it explicitly. If you're ever manually calling `.release()` then that indicates a place where the smart pointer abstraction has broken down. You want to minimize or eliminate that. Note that in the examples using the new functions there are no explicit calls to `.release()` anywhere and this is a good thing.I can't recall ever seeing a C API that conditionally deallocates the pointer passed in. Do you have an example? Most C APIs that I'm familiar with have one function that allocates a new object and a separate function that unconditionally deallocates it, acting analogously to `malloc` and `free`.
Yes, that's life when you're at the boundary with a C API.
> I can't recall ever seeing a C API that conditionally deallocates the pointer passed in. Do you have an example?
realloc()?
Generally when you have an in-out parameter, it's doing more than just releasing resources, so there's a potential for failure. And in the failure case, the caller will often retain ownership of any pointers it passed. In fact, off the top of my head, I can only think of one function that is contrary to this, and that is DeferWindowPos() in Windows, which invalidates the input handle even on failure.
OK, I'll give you that one, but that's a rather unusual case. It has complicated semantics. It is unlikely to interoperate well with any smart pointer without careful, manual work.
It doesn't take a `T**` so it doesn't seem relevant to discussions of std::out_ptr though? You won't be able to use std::out_ptr with realloc so there's no chance of making a mistake with it.
> Generally when you have an in-out parameter, it's doing more than just releasing resources
I'm still confused. What function do you have that is both releasing resources and also doing other work which might fail? Even something like `fclose` which needs to flush buffers and then release resources will always release the resources, even if the flush fails.
I'm more familiar with APIs that have:
- One (or more) functions to explicitly allocate the object
- Many functions that do work with that object and that might fail but that will never deallocate the object
- One function to explicitly deallocate the object
For example, SQLite has sqlite3_open to create a new database object, sqlite3_prepare, sqlite3_exec, etc. to operate on the database object, and sqlite3_close to deallocate the database object.
Same thing could be/has been said about std::string_view or std::span but here we are.
Like you said, a bare pointer could mean anything. This at least standardizes this particular footgun in question (which means one less reason to expose bare pointers in your API) so we are supposed to pay extra attention when we see one of those, I guess?
It's the first time I'm hearing this, and it doesn't sound like an opinion I've ever had. Those are just range-checked pointers; their ownership semantics aren't any different from those of raw pointers, and they're no less safe than raw pointers. In contrast these actually do have weird ownership semantics, and they have a propensity to introduce safety bugs into the common use cases that didn't exist before.
When I see std::string_view, nothing tells me that this may lead to memory corruption because the underlying storage may go away at any time (and the compiler will happily let this happen). New C++ features simply should not create new memory corruption footguns in addition to the existing ones, embarrassments like iterator invalidation are already bad enough (and worse than typical C memory management issues, because in C such issues are usually 'in your face', while C++ hides them beneath layers upon layers of stdlib abstractions).
Say that you have some `Person` class with a `get_name()` method that returns the person's name. Then maybe you write some code like this to use it:
Person person;
// ...
std::string_view name(person.get_name());
// Use `name` here
Is this code safe? Well it depends on the implementation of `Person::get_name`. Maybe it looks like this: std::string& Person::get_name() {
return m_name;
}
Then the code should be OK because the call will return a reference to a member of `person` and `person` will outlive `name`.But what if instead the implementation looks like this:
std::string Person::get_name() {
return m_first_name + " " + m_last_name;
}
Now you're in trouble. A temporary string will be created and the string_view will refer to that string. That temporary gets destroyed at the end of the statement and then `name` is dangling. By the time you get to use `name` it is already broken.It is very easy to make this kind of mistake. Much easier than with pointers IMO since you usually have to explicitly take a pointer to something and you can't directly get a pointer to a temporary (`std::string* p = &person.get_name()` is an error if `Person::get_name` returns `std::string`).
By contrast, getting a const reference to a temporary and then constructing a string_view out of it is not an error or even a warning. It is all done implicitly so there is no indication in the code that it is even happening. The only difference between code that is correct and code that is incorrect is a single ampersand far away in some header file.
This type of mistake probably won't get caught in code review. How often does a person really go track down and examine a header file when reviewing a pull request? Probably they're only going to look at the actual files that are being changed.
Even worse, say that `Person::get_name` is using the first implementation so the code is correct and working. But later on somebody does a refactor such `Person::get_name` uses the second implementation. Now they've broken things but they're unaware of this fact. They want to be responsible and find any problems that they might have introduced. The first step is to run a build and see if there are any complaints from the compiler. That is successful and the compiler produces no warnings.
Encouraged by this they then run all the tests. And all the tests pass! Reading memory just after it has been freed will often give you back the last thing that was stored there so the tests see the values that they expect. So with a successful build, a successful run of all the tests, and no problems spotted in code review, they confidently merge the change. And now you've got a use-after-free in your code that will eventually cause a problem.
Yes, using Address Sanitizer will catch this. But it is still a pretty easy way to introduce a bug into your program. Code that does not look at all suspicious can be completely broken.
C++ is a huge sinking ship...
Is there anything like this in the plans ?
The basic idea is you mark a file as not allowed to use some old feature, and then the code throws an error if you use one. C++11-20 were mostly about finding and adding all the little details that you actually need to write code without the bad old stuff.
C++ believes that the key to their success is backward compatibility. Even though you shouldn't use a lot of old stuff in new code, there is a lot of old C++ code out there that it isn't worth rewriting in a different language, so they cannot drop support for the old superseded stuff even though you shouldn't use it.
Clazy and cppcheck will warn about using some old constructs when there is a new/modern way that is better. However most changes of the type you want require a large redesign to implement, and if the code hasn't been touched in years that isn't going to happen.
C++ itself won't ever remove legacy just like other languages never really remove legacy. Nobody wants to be the next Python3.
And Python 3 is the success story here. You could instead easily end up being Perl 6 instead.
Many companies and many of us put in hundreds to thousands of hours moving from 2 to 3.
It is a pain, but languages are software products as well, so they either get new features to keep going on each new release or they wither and fade away.
Eventually some do still die of complexity, replaced by simpler languages, and the cycle reboots, see PL/I, Algol 60/68, ...
C and assembly enter the chat
Wouldn't you agree that the fraction of software written in C or asm has shrunk tremendously over the last decades?
ISAs have to exist but the way that code is generated for them is as varied as the landscape of high level languages.
I often have to Google for definition when I read code. Inevitably someone uses the latest feature.
Used to be foo* x=new foo(). Now it's std::shared_ptr<foo> x=std::make_shared<foo>()
It adds up, every line of code is three times longer than it used to be.
and the equivalent modern C++: auto x = std::make_shared<x>(); ...
There's `auto` for that reason. No need to duplicate the info.
And: In general code is read more often than written, and the variant with `make_shared` provides extra information on the purpose of the heap allocation. That first line with the raw pointer and new requires following all calls closely to understand the intention. (Aside from also handling the lifecycle, which would this be code which one would have to write elsewhere, your example is missing at least one `delete x` (and likely more handling, considering this being a shared, not unique, ptr)
Apps, operating systems, cars, languages, everything is being updated all the time.
Interfacing with these with a smart pointer without a helper type is kind of inconvenient, since then you need to do something like:
T* raw_owning_ptr;
foo(&raw_owning_ptr);
std::unique_ptr<T> ptr(raw_owning_ptr);
`out_ptr` and friends are a bit niche, just for interfacing with these kinds of APIs. std::unique_ptr<ADDRINFOEXW, addrinfo_deleter> holder;
ADDRINFOEXW hint = { .ai_family = AF_UNSPEC };
if (const auto result = GetAddrInfoExW(
sHost
, nullptr
, NS_ALL
, nullptr
, &hint
, std::out_ptr(holder)
, nullptr
, nullptr
, nullptr
, nullptr); result != ERROR_SUCCESS) {
// print error here
}But having malloc/free cross a library boundary (that is library A malloc and wants the caller in a different library to call free) is also a code smell in general and potentially very problematic. So you'll be generally doing custom deleters regardless
That last is also why no language can afford to get rid of anything (see python 3 which took over a decade to catch on), someone is using the old thing in code they don't want to touch.
At the rate the committee adds stuff it feels like it is a full time job just to keep up.
Also is there any initiative within C++ to do a subset dialect with bowling alley guard rails? Something analog to the old C++ JFS standard, or something analog to dlang '-betterC' dialect flag?
You don't have to keep up with all the stuff it adds. If you actually need a certain thing C++ has added -- that you're unaware of -- you'll naturally find it when you go looking for it.
Otherwise, it's best to just stick with the feature-set that you know. KISS/YAGNI/if it ain't broke, don't fix it (but if it is broke, find a better way). Et other cliches.
> This week, let’s continue exploring the new world of C++23. We are going to discuss two new standard library functions and their outputs (std::out_ptr, std::inout_ptr), two new standard library types (std::out_ptr_t, std::inout_ptr_t).
IMNSHO the two lists in parentheses should each be next to the thing referring to them, like this:
This week, let’s continue exploring the new world of C++23. We are going to discuss two new standard library functions (std::out_ptr, std::inout_ptr) and their outputs, two new standard library types (std::out_ptr_t, std::inout_ptr_t).
BTW, P2723[1] tries to solve the same problem by zero-initializing everything by default. I'm not a fan of it. It's less elegant, it incurs potential performance cost and zero isn't always the right default.
[1] - https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2022/p27...
I think cppfront[0] is the way to go if you want to write a safer language on top of C++, you can watch the talk about it here[1].
[0] https://github.com/hsutter/cppfront [1] https://www.youtube.com/watch?v=ELeZAKCN4tY
I'm looking at how to fit rust into our project, but it isn't easy. I can report already that bad programmers in rust write worse code than great programmers in C++...
It's like stopping huffing paint to start huffing petrol.
Also if your only complain in syntax then is just your taste, I would have considered if you have complains about issues with the language, one that I can think of is async/await that is a WIP.