c++auto x:_C2x:未来的C标准

c++auto x:

image

A cue to the events that may come in my day.

提示可能发生在我这一天的事件。

(‘Doctor Zhivago’, Boris Pasternak)

(“日瓦戈医生”,鲍里斯·帕斯捷尔纳克(Boris Pasternak))

I’ll be honest: I don’t write in pure C that often anymore and I haven’t been following the language’s development for a long time. However, two unexpected things happened recently: С won back the title of the most popular programming language according to TIOBE, and the first truly interesting book in years on this language was published. So, I decided to spend a few evenings studying material on C2x, the future version of C.

我会说实话:我不再使用纯C语言编写代码了,而且很长一段时间以来我都没有关注这种语言的发展。 但是,最近发生了两件出乎意料的事情:СTIOBE 赢得了最受欢迎的编程语言的称号,并且出版了多年来关于该语言的第一本真正有趣的书。 因此,我决定花几个晚上学习有关C2x(C的未来版本)的资料。

Here I will share with you what I consider to be its most interesting new features.

在这里,我将与您分享我认为最有趣的新功能。

委员会,标准及所有其他 (The Committee, the Standard and all that)

I am sure most of you know how C is developed, but, for anyone who doesn’t know let me first explain the terminology, and will then briefly retell the story of the language.

我敢肯定,你们大多数人都知道C是如何开发的,但是,对于任何不知道的人,让我先解释一下术语,然后再简要介绍一下该语言的故事。

In 1989 the already extremely popular programming language, C, reached new heights of recognition, becoming both the American national (ANSI) and the international (ISO) standard. This version of C was known as C89, or ANSI C to differentiate it from the numerous semi-compatible dialects that had existed previously.

1989年,已经非常流行的编程语言C达到了公认的新高度,成为美国国家( ANSI )和国际( ISO )标准。 此版本的C被称为C89或ANSI C,以将其与以前存在的众多半兼容方言区分开。

A new version of the language standard is released approximately once every ten years. At the present time there are four versions in existence: the original C89, C99, C11 and C18. It is not known when the next version will be published, so the version currently being worked on is referred to as C2x.

语言标准的新版本大约每十年发布一次。 目前存在四个版本:原始的C89,C99,C11和C18。 目前尚不清楚何时发布下一个版本,因此当前正在使用的版本称为C2x。

Changes to the standard are made by a special group, the so-called WG14. It comprises interested representatives of the industry from various countries.

标准的更改由一个特殊的小组进行,即所谓的WG14。 它由来自各个国家的感兴趣的行业代表组成。

In the specialist English-language literature this group is often referred to as the ‘Committee’, so that is what I am going to call it here as well.

在专业的英语文学中,该组通常被称为“委员会”,因此我在这里也将其称为“委员会”。

The Committee receives proposals from those involved, each proposal being given a designation(e.g. N2353). Proposals usually include: the reason for introducing changes, references to other documents, and specific changes to the Standard. Proposals can come in several versions, each of which is given a unique designation.

委员会从有关人员那里收到提案,每个提案都有一个名称(例如N2353 )。 提案通常包括:引入更改的原因,对其他文档的引用以及对标准的特定更改。 提案可以有多个版本,每个版本都有一个唯一的名称。

Returning to our topic for a moment, I have split this article into three parts, and have ordered them according to the likelihood of the relevant changes being made to the standard. The three parts are as follows:

回到主题,我将本文分为三个部分,并根据对标准进行相关更改的可能性对它们进行了排序。 这三个部分如下:

  1. Proposals the Committee has already accepted.

    委员会已经接受的提案。
  2. Proposals received positively but returned to the authors for revision.

    提案收到好评,但返回给作者进行修订。
  3. What I consider to be the ‘juiciest’ proposals: rumoured unpublished proposals, being discussed behind the scenes by members of the Committee.

    我认为最“有益”的建议:传闻未发表的建议,委员会成员在幕后进行讨论。

委员会接受的提案 (Proposals accepted by the Committee)

strdup和strndup函数 (strdup and strndup functions)

I may appear ignorant when I say that I wasn’t aware these functions weren’t in the standard C library. What could be more obvious and simpler than copying strings? But no, C isn’t like that. C doesn’t like its users.

当我说我不知道​​这些功能不在标准C库中时,我可能显得一无所知。 有什么比复制字符串更明显和更简单的呢? 但是不,C不是那样的。 C不喜欢它的用户。

So, 20 years later, we are getting the strdup and strndup functions!

因此,20年后,我们获得strdupstrndup函数!

#include <string.h>

char *strdup (const char *s);
char *strndup (const char *s, size_t size);

It is nice to know that even the Committee accepts the inevitable.

很高兴得知,即使委员会也接受了不可避免的情况。

属性 (Attributes)

Developers of major C compilers have a favourite game they play: coming up with extensions to the language most often expressed through attributes of declarations and definitions. The language itself, of course, does not provide any special syntax for such things, so each person needs to do what they can to be creative.

主要C编译器的开发人员喜欢玩的游戏:提供对语言的扩展,这些语言最常通过声明和定义的属性来表示。 当然,语言本身并没有为此类事情提供任何特殊的语法,因此每个人都需要尽自己的能力去发挥创造力。

In order to – somehow – to sort out this mess without coming up with dozens of new keywords, the Committee thought up a syntax-to-rule-them-all. In a nutshell, a standard syntax for specifying attributes will be approved as part of the next version. Here is an example from the proposal:

为了以某种方式在不提出许多新关键词的情况下解决这些混乱局面,委员会考虑了所有规则的语法。 简而言之,用于指定属性的标准语法将被批准为下一版本的一部分。 这是提案中的一个示例:

[[attr1]] struct [[attr2]] S { } [[attr3]] s1 [[attr4]], s2 [[attr5]];

Here, attr1 relates to s1 and =s2=; attr2 relates to the struct S definition; attr3 relates to the struct s1 type; attr4 to the s1 identifier; and attr5 to the s2 identifier.

这里, attr1s1=s2= ; attr2struct S定义有关; attr3struct s1类型有关; attr4s1标识符; 和attr5s2标识符。

The Committee has already voted to include the attributes in the standard, but there is still a long time to wait before the updated version of the standard is published. Nevertheless, proposal authors are already playing with their new toy. Here are some of the proposed attributes:

委员会已经投票通过将属性包含在标准中,但是要等到发布更新版本的标准之前,还有很长的时间要等。 尽管如此,提案作者已经在玩他们的新玩具。 以下是一些建议的属性:

  1. The deprecated attribute allows you to mark a declaration as obsolete, which allows compilers to issue appropriate warnings.

    deprecated属性使您可以将声明标记为过时,从而允许编译器发出适当的警告。

  2. The fallthrough attribute can be used to explicitly mark the places in the switch case branches, where the control flow is supposed to cross case boundaries.

    fallthrough属性可用于显式标记开关案例分支中控制流应该跨越案例边界的位置。

  3. Using the nodiscard attribute you can explicitly specify that a value returned by the function needs to be processed.

    使用nodiscard属性,您可以显式指定该函数返回的值需要处理。

  4. Where a variable or function is not used deliberately, you can mark it with the maybe_unused attribute (instead of the idiomatic (void) unused_var).

    在没有故意使用变量或函数的地方,可以使用maybe_unused属性(而不是惯用的(void) unused_var )标记它。

  5. A function not returning to the call location can be marked with the noreturn attribute.

    可以使用noreturn属性标记不返回到呼叫位置的功能。

老式函数参数声明样式(K&R) (Old-school function parameter declaration style (K&R))

‘K&R declaration’ (read “when types are specified after the brackets” or, “I don’t understand old code in C”) is a form of function parameter declaration that was already out-of-date way back in 1989. It is finally going to be burnt with fire. In other words, you won’t be allowed to do this anymore:

“ K&R声明”(请阅读“在括号后指定类型时”或“我不理解C中的旧代码”)是一种函数参数声明的形式,该形式早在1989年就已过时。最终将被火焚毁 。 换句话说,您将不再被允许这样做:

long maxl (a, b)
long a, b;
{
    return a > b ? a: b;
}

Enlightenment has finally come to code in C! Function declarations will at last actually do what people expect them to:

终于有了C语言的启发! 函数声明最终将实际执行人们期望它们执行的操作:

/* function declaration without arguments */
int no_args();

/* also function declaration without arguments */
int no_args(void);

有符号整数表示 (Signed integer representation)

What has felt like an endless saga is nearing completion, it would seem. The Committee has come to terms with the fact that there are no such things as unicorns or mythical architectures, and programmers in C are dealing with Two’s complement signed integer representation.

看起来似乎无尽的传奇即将完成。 委员会已经接受了这样一个事实,即没有独角兽或神话般的架构,C语言中的程序员正在处理Two的补码有符号整数表示形式。

In its present form this clarification simplifies the standard a little, but in future it should make it possible to get rid of the language’s favourite undefined behaviour.

以目前的形式,这种澄清使标准稍有简化,但将来它应该有可能摆脱该语言最喜欢的不确定行为。

正在处理的提案 (Proposals being worked on)

While it can be said that the changes listed above already exist in our reality, the following group of proposals is still being developed. Nevertheless, the Committee has given them provisional approval and, assuming the authors show due diligence, they should definitely be accepted.

可以说,上面列出的更改已经存在于我们的现实中,但仍在制定以下建议组。 不过,委员会已给予他们临时批准,并假设作者表现出尽职调查,则绝对应该接受他们。

匿名函数参数 (Anonymous function parameters)

I regularly write 1-2 trial programs in C a week. And, quite honestly, I have long grown tired of having to specify the names of unused arguments.

我每周定期在C中编写1-2个试用程序。 而且,老实说,我早已厌倦了必须指定未使用参数的名称。

Implementing one of the proposals positively assessed by the Committee would mean that we wouldn’t have to keep specifying the names of parameters in function definitions:

实施由委员会积极评估的建议之一将意味着我们不必在功能定义中继续指定参数名称:

int main(int, char *[])
{
    /* No hassle! */
    return 0;
}

It’s a small thing – but welcome!

这是一件小事,但欢迎您!

旧的新关键字 (The old new keywords)

After a very loooong transition period the Committee, finally, decided to accept, erm, ‘new’ keywords into the language: true, false, alignas, alignof, bool, static_assert and others. It will finally be possible to drop headers like <stdbool.h>.

经过一段漫长的过渡期之后,委员会最终决定接受“ erm ”(新) 关键字加入该语言: truefalsealignasalignofboolstatic_assert等。 最终将有可能删除诸如<stdbool.h>类的标头。

在源文件中包含二进制文件 (Including binary files in the source file)

The option of including binary data from files in the executable file is something all game developers are going to find unbelievably useful:

所有游戏开发人员都会发现在可执行文件中包含来自文件的二进制数据的选择令人难以置信地有用:

const int music[] = {
   #embed int "music.wav"
};

It’s my belief that the Committee has realises that the community knows where their next meeting is being held, and that this preprocessor directive will be accepted without questions.

我相信委员会已经意识到社区知道下一次会议的举行地点,并且可以毫无疑问地接受该预处理程序指令。

告别,NULL –或在起始块上准备好nullptr (Farewell, NULL – or nullptr ready on the starting blocks)

It would seem that the problematic NULL macros are being replaced with the keyword nullptr, which will be equivalent to the expression ((void*)0) and, in the case of type conversion, will have to remain a pointer type. Any use of NULL should be accompanied with a compiler warning:

似乎有问题的NULL宏已替换为关键字nullptr ,它与表达式((void*)0)等效,并且在类型转换的情况下,必须保留指针类型。 NULL的任何使用都应伴随编译器警告:

/* I always forget why the cast is necessary. */
int execl(path, arg1, arg2, (char  *) NULL);

/* But happiness is just round the corner */
int execl(path, arg1, arg2, nullptr);

If this example make no sense to you, then take a look at the Linux documentation under man 3 exec and you will find your enlightenment there.

如果这个示例对您没有意义,请查看man 3 exec下的Linux文档,您将在这里找到启发。

改革标准库中的错误处理 (Reform of error processing in the standard library)

The processing of standard library function errors has been a longstanding problem in C. The combination of unfortunate solutions in various versions of the standard, the conservative stance of the Committee and reverse compatibility issues have all got in the way of finding a solution that suits everyone.

标准库功能错误的处理一直是C语言中长期存在的问题。各种版本的标准中不幸的解决方案,委员会的保守立场以及反向兼容性问题的结合,都阻碍了找到适合所有人的解决方案。 。

And here, finally, is someone prepared to propose a solution for compiler developers, the super-conservative Committee and for us mere mortals:

在这里,最后,是有人准备提出对编译器开发人员,超级保守的委员会和我们凡人的解决方案:

[[ oob_return_errno ]] int myabs (int x) {
  if(x == INT_MIN ) {
          oob_return_errno ( ERANGE , INT_MIN ) ;
  }
  return (x < 0) ? -x : x;
}

Let me draw your attention to the oob_return_errno attribute. This means that the following functions will be generated from this template function:

让我引起您对oob_return_errno属性的关注。 这意味着将从此模板函数生成以下函数:

  1. A function returning the structure with an error flag and the result of the work of the (struct {T return_value; int exception_code}) function.

    该函数返回带有错误标志的结构以及( struct {T return_value; int exception_code} )函数的工作结果。

  2. A function returning the result of the work of the function, and ignoring possible errors in the arguments, leading to undefined behaviour.

    函数返回函数工作的结果,并忽略参数中可能的错误,从而导致未定义的行为。
  3. A function terminating execution in the case of an error in the arguments.

    在参数错误的情况下终止执行的函数。
  4. A function replacing errno, that is, exhibiting ordinary behaviour.

    替代errno的功能,即表现出正常的行为。

The compiler is offered a choice between these options, depending on how the programmer uses a given function:

根据程序员如何使用给定函数,为编译器提供以下选项之一:

bool flag;
int result = oob_capture(&flag , myabs , input) ;
if (flag) {
    abort ();

In this case, if the function has been carried out properly, this is shown with a flag, while errno is not affected. Function calls saving the error code to the variable, for example, look similar.

在这种情况下,如果功能已正确执行,则会显示一个标志,而errno不受影响。 例如,将错误代码保存到变量的函数调用看起来很相似。

The actual syntax, it would seem, will yet change, but it is a good thing that the Committee is at least thinking in this direction.

实际的语法似乎仍会改变,但是委员会至少在朝这个方向思考是一件好事。

谣言 (Rumours)

The author of “Effective C”, along with other Committee members, answered questions from members of the Hacker News community. Lots of things overlap with what we have noted above. But there are a couple of points which are important for programmers. These have not been formulated as proposals, as such, however Committee members are hinting that work might be underway in these areas.

“ Effective C”的作者以及其他委员会成员回答了Hacker News社区成员的问题。 许多事情与我们上面提到的重叠。 但是有几点对程序员很重要。 这些尚未作为建议书拟定,但是,委员会成员暗示,这些领域的工作可能正在进行中。

类型运算符 (typeof operator)

The typeof keyword was implemented a long time ago in compilers and makes it easier to write correct macros. Here is a textbook example:

typeof关键字是实现在编译器很长一段时间以前,可以更容易地编写正确的宏。 这是一个教科书示例:

#define max(a,b)                                \
    ({ typeof (a) _a = (a);                     \
    typeof (b) _b = (b);                        \
    _a > _b ? _a : _b; })

Martin Sebor, a developer from Red Hat and a Committee member, maintains that a relevant proposal is already being worked on and will very likely be approved.

Red Hat的开发人员兼委员会成员Martin Sebor坚称,相关提案已在制定中,很可能会获得批准。

Keeping my fingers crossed!

保持我的手指交叉!

延迟运算符 (defer operator)

Some programming languages, including ones implemented by Clang and GCC, allow you to bind freed-up resources to the lexical scoping of variables or, to put it more simply, to call given code when the control flow goes outside the scope of the variable.

某些编程语言(包括由Clang和GCC实现的编程语言)允许您将释放的资源绑定到变量的词法作用域,或者更简单地说,当控制流超出变量范围时调用给定代码。

Pure C doesn’t have this option nor ever has, but compilers have been implementing the cleanup(<cleanup function>) attribute for a long time:

Pure C既没有此选项,也没有,但是编译器已经很长时间实现了cleanup(<cleanup function>)属性:

int main(void)
{
   __attribute__((cleanup(my_cleanup_function))) char *s = malloc(sizeof(*s));
   return 0;
}

Robert Seacord author of “Effective C” and member of the Committee has admitted that he is working on a proposal along the lines of the keyword defer from Go:

罗伯特·希科德(Robert Seacord)是《有效C》的作者,也是委员会的成员,他承认他正在defer Go的关键字defer进行提案:

int do_something(void) {
    FILE *file1, *file2;
    object_t *obj;
    file1 = fopen("a_file", "w");
    if (file1 == NULL) {
      return -1;
    }
    defer(fclose, file1);

    file2 = fopen("another_file", "w");
    if (file2 == NULL) {
      return -1;
    }
    defer(fclose, file2);

    /* ... */

    return 0;
}

In this example, the fclose function will be called with the file1 and file2 arguments, in any case where the program goes outside the body of the do_something function.

在此示例中,在程序超出do_something函数主体之外的任何情况下,都将使用file1file2参数调用fclose函数。

Vive la révolution!

万岁革命!

结论 (Conclusions)

Changes to C are like genetic mutations: they don’t happen often, rarely are viable, but, in the end, they push the evolution forward.

C的变化就像基因突变:它们不经常发生,很少是可行的,但最终,它们推动了进化。

The most recent unfortunate changes to C occurred ten years ago. And the most recent quality leap forward in terms of development of the language happened over 20 years ago. And, by all accounts, the members of the Committee have now decided to consider moving forwards in respect of the new iteration of the standard.

C的最新不幸更改发生在十年前。 就语言的发展而言,最近的一次质量飞跃发生在20年前。 而且,从所有方面来看,委员会成员现在已经决定考虑就该标准的新版本进行推进。

So, to conclude: use static analysers, run Valgrind as often as possible and try not to write overly-big programs in C!

因此,可以得出以下结论:使用静态分析器,尽可能频繁地运行Valgrind,并尽量不要用C编写太大的程序!

PS I think the “first truly interesting book” thing was an overstatement on my part. Someone recommended a book entitled ‘Modern C’ written by a member of the committee, and that would definitely be worth a read.

PS:我认为“第一本真正有趣的书”对我而言是夸大其词。 有人推荐由委员会成员写的一本名为“现代C”的书,这绝对值得一读。

翻译自: https://habr.com/en/company/badoo/blog/512802/

c++auto x:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值