In short, restrict is supposed to tell the compiler that the pointers cannot point into the same memory location. Which is very useful for, say, function arguments and further compiler optimization. In scientific computing, restrict is very widely used.
Currently, restrict keyword is only a part of C99, but not a part of C++. We know that a lot of C++ compilers support __restrict__ as an extension. This question also talks in detail about what restrict and __restrict__ do.
Now, the discussion in the aforementioned question happened a long time ago and does not talk about C++17, C++20, nor plans for future standards. I found n3988 proposal that discusses restrict-like aliases in C++, complexities with richer syntaxis in C++, and potential remedies.
According to the IBM blog (2014), n3988 was encouraged for future work.
This question talks about the history of restrict and C++ without anything conclusive regarding the actual implementation and mentions the papers I already listed or the one mentioned in the comments (p1296).
I was not able to find anything beyond that on the plans of supporting restrict in the upcoming C++ (as far as I know, it's not a part of C++17). It seems like a very useful functionality, so I wonder
if I missed something in terms of proposals/discussion?
is there other information on the restrict usage in C++?
are there alternative ways to make the compiler optimizations (allowed by __restrict__) possible by using only "standard" functionality?
Nothing like C’s restrict is in even C++20. The paper already mentioned was well-received at a preliminary presentation in November 2018, perhaps because it avoids the critical difficulty with a qualifier—that no one, even in C, understands how it interacts with the rest of the type system. Part of this is because adding restrict doesn’t change the meaning of any one pointer, but affects its relationship with some set of other pointers (whose membership is not well-specified) based on what arithmetic is performed with them later. Another part is because C++ allows so many operations with types: what would std::vector<T *restrict> mean, and what would be the type of indexing a std::vector<T> &restrict?
Just what practical optimization opportunity will be offered by such a contract-based approach is not yet clear; there are still many unanswered questions about contracts and optimization in general.
Related
C++20 introduces <format>(and sooner C++23 introduces <print>). I like those methods, and I always try to use std::format when it's supported rather than use a series of <<.
But I notice that this evolution seems to only appear in the output. Why isn't there something like <scan> for input?
std::format and std::print are already quite a big library addition in itself and I could image that the limited resources for the standard committee to consider the addition of additional features didn't allow them to consider an input equivalent at the same time.
It might also be that the committee wanted to collect more experience with std::format/std::print first before adding an input equivalent or that there are objections to such an addition in principle, in the proposed implementation details or the priority of such an addition.
I couldn't find any definitive statements pointing towards any of these directions and I have no insider knowledge.
Anyway, the committee is still considering a std::scan proposal as follow-up to the std::format proposal, see https://github.com/cplusplus/papers/issues/493 for a log of the procedure the proposal has gone through so far. You can also see there polls on design directions, etc. There seems to not have been much activity since 2019, but I am not sure whether this really means anything or not.
In a reddit thread here from March 2022, Elias Kosunen, one of the authors of the proposal and author of scnlib mentions that there are still some unsure design questions that need to be made sure of before going forward with the proposal, hoping to be able to target C++26, but acknowledging that a farther delay would be preferable to adding a "half-baked" design to the standard.
This topic is controversial, but I'm in the camp which believes that preconditions and class invariants should be guarded by asserts which terminate the program if the contract of the corresponding SW component is violated - as long as the runtime cost for the assertion checks is not a performance bottleneck.
I really like optional types and use them a lot, but for me the standard library implementations of std::optional are unusable as of now, since first the dereferencing of an optional does not perform checks whether it contains a value, and second none of the major c++ implementations support/implement assertions within standard library functions as of now.
From the use of std::optional I have seen over the years, I cannot recall a single instance where a std::optional was used in such a manner and quantity, such that precondition checks would be a performance bottleneck and prohibitive. For instance, I have never seen that somebody implemented a mask image as an array of std:optional's.
My question: Is there any proposal out already (e.g. for c++22), which adds contract features to the standard library, in particular std::optional?
Yes, I'm aware of the value method which is "guarded" by an exception.
First, I'm not a big fan of non-exceptional control flow using exceptions (have you ever tried to debug such code).
Second, I believe the strength and safety of a type should judged by its weakest link.
I can't comment yet, hence I comment on the answer by Nicol Bolas here:
Thanks for the answer, but I frankly I don't think it answers my question. Just to clarify. I'm not asking for a proposal which mandates that std::abort is called on contract violations (of an "expect" close). Instead, I'm asking whether there are any plans to add contract annotations to the standard library following the P0788 proposal. I agree that the standard should not mandate how specific implementations should deal with such contract violations.
This is kind of moot for the immediate future, since contracts was removed from C++20 for some reworking. However, I think the remaining text still applies:
Is there any proposal out already (e.g. for c++22), which adds design by contract support to the standard library, in particular std::optional?
Quite the opposite: the proposal P0788 was adopted and folded into the C++20 working paper, which states that preconditions/postconditions are not to be mandated to be implemented by the contract feature. The specific intent of P0788 was to prevent formalized requirements on implementations to use contracts for these things (or concepts for similar conditions):
Let’s avoid any specification that demands any particular technology by which implementations must comply with Library specifications.
Implementations are permitted to express such conditions as contracts, but are not required to. By adopting P0788, the committee is effectively considering such things to be a matter of implementation quality, not formal specification.
C++ is not a safe language, and contracts are not intended to make it so. Violating contracts is a programming error and yields UB, and that's how the standard sees things. And by design, there is no way for you to force your desire for safety upon those who don't want it.
Answer to my own question. Thanks for the discussion which pointed in the right direction.
Currently, the dereference operator of std::optional is annotated with an "Requires" clause.
In the spirit of P0788, I'd expect the Requires clause to be changed to Expects in the near future:
Let’s make it a goal, over time, to eliminate all Requires: elements from our Library
specifications, preferring our new elements instead.
Furthermore, standard library implementations are permitted to any technology to meet "Expects" specifications.
Let’s permit an implementation to use Contracts attributes [P0542R1] and/or any other
technologies to meet Expects: and Ensures: specifications.
So far, so good. Only the following statement makes it a little more tricky:
Let’s consider user code that relies on any specific technology on the part of an implementation to be ill-formed, with no diagnostic required
My interpretation of the above that users can't rely that standard implementations will guard Expects in any specific way or at all, but they may.
To the question:
Is there any proposal out already (e.g. for c++22), which adds contract features to the standard library, in particular std::optional?
Yes, contract annotations are already part of the standard.
It is up to the specific library implementation how to deal with "expect" clauses.
It appears that Concepts can do everything you could have done using SFINAE based techniques, only much better. The list of advantages includes increased readability of overload resolution and enabling to make compiler diagnostics substantially less verbose.
One option, given that all of these Concepts' features are already part of the new draft, is that some or all of these SFINAE related helper templates be declared deprecated.
My main concern here is feature fragmentation.
My question is whether such a proposal for deprecation has in fact been submitted?
That seems like a rather pointless thing to do at this point. There is a lot of code out there using these templates, they won't be removed in the foreseeable future anyway.
Even removing trigraphs and the conversion from string literal to non-constant char* took quite a while, and at least the former was not even undisputed. (IBM wanted to keep them iirc.) Those templates have and had valid uses in current modern C++; they are here to stay†.
Note that deprecating a feature in the C++ standard is a fairly drastic step, placing it under review for future removal. It is meant to be a temporary state; either the feature gets removed at some point, or is restored to be non-deprecated:
With the release of a new C++ standard, we get an opportunity to revisit the features identified for deprecation, and consider if we are prepared to clear any out yet, either by removing completely from the standard, or by reversing the deprecation decision and restoring the feature to full service.
In an ideal world, the start of every release cycle would cleanse the list of deprecated features entirely, allowing the language and library to evolve cleanly without holding too much deadweight. In practice, C++ has some long-term deprecated facilities that are difficult to remove, and equally difficult to rehabilitate. Also, with the three year release cadence for the C++ standard, we will often be considering removal of features whose deprecated status has barely reached print.
From P0619R3, emphasize mine.
†At least for now. I'm not a member of the committee, so I can only speculate, but I would not rule out the possibility of deprecation at some point in the future, after concepts have settled in and if it becomes evident that the old helper templates do more harm than good.
The title says it all. I am curious why is the restrict keyword not part of C++ ? I don't know much about C++, and I'm still not able to find anything online that would give a reason blocking this. Does anyone know what terrible things would happen, if a C++ standard would use this keyword similarly to the way C does? Is it just not needed at all?
More explanation: It is not about using it, perhaps I will not have any benefit from this keyword in my whole life. This question is only about curiosity, since restrict is part of C since C99, that is 15 years.
Read this as well:
I'm interested in technical reasons, not opinions like "They just didn't like, it is not cool enough"
There are several issues in defining "restrict" in C++, some of them are listed in WG paper N3635: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3635.pdf "Towards restrict-like semantics for C++"
Some possible issues with restrict in C++ are:
Restrict Class members and indirection with “this pointer”
Passing of restrict qualifiers into functions, functors, lambdas, and templates
Escaping of restrict pointer values inside functions
Overlapping array members, strides
Document also list several C++ compilers with limited "restrict" support for C++.
There is also interesting history note in N3635 about non-inclusion of restrict to C++:
At the time of reviewing C99 feature inclusion in C++ during the Mont Tremblant meeting, restrict was considered but was waiting a paper proposal although none came forward....
Restrict is a C99 feature and was never designed to work in class abstractions and it may have to do with that pointers are not common in C++. ... it was designed for fine-grain aliasing for C, but not well-designed for type-based aliasing in C++
Not to detract from osgx's answer, but - there is a somewhat more up-to-date paper, N3998 by Finkel, Tong, Carrouth, Nelson Vandevoode and Wong, from May 2014:
Towards restrict-like aliasing semantics for C++
And an ever newer one from 2018:
[[assert: std::disjoint(A,nA, B,nB)]]: Contract assertions as an alternate
spelling of ‘restrict’
(Thanks #MCCCS for pointing the last one out.)
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
As you may have heard, the last meeting of the C++ standards committee voted to remove concepts from the next C++ standard. Of course, this will affect other features and would seem to throw the standard wide open again. If that is the case, which other features do you think should be stripped away (or added), and why?
Links:
Removal of Concepts -- Danny Kalev (on the decision to remove concepts)
Simplifying the use of Concepts -- Bjarne Stroustrup (on the problems with concepts as they look now)
The Long Pole Gets Longer -- Martin Tasker (on the impact to the schedule for C++0x if concepts have to be fixed)
The C++0x "Remove Concepts" Decision - Stroustrup on the issue on Dr. Dobbs
Trip Report: Exit Concepts, Final ISO C++ Draft in ~18 Months - Herb Sutter
Concepts Get Voted Off The C++0x Island - Jeremy Siek defending the current Concepts spec
What Happened in Frankfurt? - Doug Gregor on C++Next (on the history and removal of Concepts).
Of course, this will affect other
features and would seem to throw the
standard wide open again.
Hardly. They still want to wrap up the standard soon, which is one of the main reasons for removing concepts. Making it "wide open" to unrelated changes would just throw away everything they gained by ditching concepts.
Anyway.... Of the remaining C++0x additions, I can't think of anything else I'd want to remove. I agree with their decision regarding concepts though. Stroustrup's paper really outlined some serious problems, The current specification for concepts would admittedly simplify template error messages, but it would do so by dramatically reducing the usefulness of generic programming -- a price I'm not willing to pay.
When I first read that paper, it scared me, because I assumed it was too late in the process for making serious changes to the spec. Turns out it wasn't, and the committee was willing to take dramatic action.
But apart from this, I think C++0x is in good shape. The remaining new features all look worthwhile.
Of course, there are plenty of existing features I'd love to remove. Primarily the vector<bool> specialization. There are other popular examples of features that didn't work out (the export keyword, exception specifications), but the vector specialization is the only one of them that can't be ignored. As long as we don't try to export templates, it doesn't matter that the keyword exists (and isn't implemented by compilers), and we can just refrain from using exception specs, but every time we need a vector of bools, we're bitten by the stupid premature optimization that slipped into the current standard.
Unfortunately, it seems like they've given up on removing it. (Last I checked, it wasn't even deprecated).
Of course, plenty of old C cruft could be ditched too, but recently, I've discovered that the one change I'd really love to see is...... ditching the Iostreams library. Toss it out, and build a new STL-style I/O library based on generic programming.
The current OOP-styled Iostreams library is ugly, slow, overcomplicated and inflexible. There's too much voodoo involved in defining new streams, too few standard stream types involved, too little flexibility (the problem that made me realize how limited the library is, was that I needed to extract a float from a string. Easy to do with stringstream, but if you need to do it often, you don't want to have to copy the input string every time (as the stringstream does) -- where's the stream that works on an existing iterator range? Or a raw array, even?)
Throw IOstreams out, develop a modern replacement, and C++ will be vastly improved.
And perhaps do something about the string class as well. It works sort of ok'ish as it is now, but really, what's with the huge number of member functions? Most of them would work better, and be more general, as free functions. Too much of the standard library relies specifically on the string class, when it could in principle work with any container, or even an iterator (std::getline, I'm looking at you)
Personally, I want C++ to finally break away from C. No more pre-processor, no more header files. I basically want D, but without all the stuff that D tacks on, using the STL.
None, I think the rest of the draft was great - a large number of very small pieces that can be correctly implemented independently, allowing vendors to evolve toward complete support and allowing users to take a "shopping list" approach.
Quite a different situation with contracts, as they were like a whole new parallel type system and would have been very likely to have led to different compilers ending up with their own backward compatibility problems, very similar to CSS in web browsers.
There are two things I think should be added to C++0x, I've thought of both these myself and then found that others have suggested them before but it doesn't seem like they're going to happen.
1. Defaulting Move Constructors and Move Assignment Operators
Writing a move constructor is a manual and error prone activity, if a member is added it must be added to the move constructor and assignment operators and std::move must be used religiously. That's why I think these functions should be defaultable.
movable(movable&&) = default;
movable& operator=(movable&&) = default;
Edit (2009-10-01): Looks like this is going to happen after all.
2. Override Type Deduction for Expression Templates
Expression templates often define types that should not be used directly, a case in point is the return value of std::vector<bool> operator[](size_type n), if auto or decltype are used on this kind of object unexpected behaviour may ensue.
Therefore a type should be able to say what type it should be deduced to be (or prevent deduction using = delete syntax).
Example for vector addition.
// lazy evaluation of vector addition
template<typename T, class V1, class V2>
class vector_add {
V1& lhs_;
V2& rhs_;
public:
T operator[](size_t n) const
{ return lhs_[n] + rhs_[n]; }
// If used by auto or decltype perform eager creation of vector
std::vector<T> operator auto() const
{
if (lhs_.size() != rhs_.size())
throw std::exception("Vectors aren't same size");
std::vector<T> vec;
vec.reserve(lhs_.size());
for (int i = 0; i < lhs_.size(); ++i)
vec.push_back(lhs_[i] + rhs_[i]);
return vec;
}
To me the problem is not what other features should be stripped away, but how complex will other features be after concepts have been removed. That and how much longer will it take for the rest of the features to be rephrased without concepts.
A lot of features assumed that concepts would be accepted into the language and the wording is expressed in terms of concepts. (I wonder if any proposed feature depends on concepts).
I also wonder how other libraries will evolve (think boost::type_traits) to take the niche left by concepts. Part of what concepts provided can be implemented (even if in a more cumbersome way) in terms of traits applied to the type arguments.
To me, the most important thing that concepts added to the language was an expressive formulation of compilation errors, which is nowadays one of the places where C++ is most criticized.
R.I.P. concepts.
Do whatever you want with concepts, but for god's sake keep threads and atomics, we absolutely need them. Perhaps add thread groups and support for cooperative threads a.k.a. fibers. IMO these are far more important than concepts, because everyone uses/will soon be using threads.
I'd like to remove =delete.
There's already a common and accepted idiom for acheiving the same effect (declare the function in question as private). I think this feature will just generate lots of 'I used =delete to remove a base class function from my derived class, but it can still be called using a base class pointer' questions.
Not to mention confusing people between the (now) two meanings of the delete keyword.
Strip away the pages of error messages on template code!
IIRC concepts should solve a big C++ coder problem: Human readable error messages for the STL. Its bad news that this issue isn't addressed.
The un-named function / lambda function stuff makes me nervous. Function objects are perfectly good and are explicit, thus easier to read and find.
On the other hand I kinda liked concepts, though I certainly would not have used them every day.