gpt4 book ai didi

自动和作用域的 C++ 初始化

转载 作者:行者123 更新时间:2023-11-30 03:02:57 25 4
gpt4 key购买 nike

谁能给我指点 C++ 标准中的一个引用,它保证函数 foo1() 中的自动 char* qfoo1() 中调用 p = bar() 后,将始终进行初始化。我已经习惯于像 foo2() 那样创建一个新 block ,并且想知道我是否对优化编译器过于 block 化和偏执。或者我的偏执是正确的,不应该假设编译器不会优化代码使得 p = bar() 总是在 q(p) 之前被调用?谢谢!

#include <stdio.h>
#include <stdlib.h>
#include <strings.h>


char* bar()
{
char* t = (char*)malloc(15);
strcpy(t, "Hello World!");
return t;
}

void foo1(void)
{
char* p = NULL;

printf("foo1: do some stuff\n");

p = bar();

printf("foo1: do some more stuff\n");

char* q(p);

printf("foo1: q says:%s\n", q);

free(p);
}

void foo2(void)
{
char* p = NULL;

printf("foo2: do some stuff\n");

p = bar();

printf("foo2: do some more stuff\n");

// is this block necessary?
{
char* q(p);

printf("foo2: q says:%s\n", q);
}

free(p);
}

int main(int ac, char* av[])
{
foo1();
foo2();
return 0;
}

最佳答案

由于 sequence points 的存在,您可以安全地假设 p = bar() 将在 char * q(p) 之前发生.

我现在不能让自己涉足 C++ 标准,但我可以给你 C99 标准的等价物,我希望它能让你充分放心:

5.1.2.3:

Accessing a volatile object, modifying an object, modifying a file, or calling a function that does any of those operations are all side effects, which are changes in the state of the execution environment. Evaluation of an expression may produce side effects. At certain specified points in the execution sequence called sequence points, all side effects of previous evaluations shall be complete and no side effects of subsequent evaluations shall have taken place.

附件 C: (强调我的)

The following are the sequence points described in 5.1.2.3:

  • The call to a function, after the arguments have been evaluated.
  • The end of the first operand of the following operators: logical AND &&; logical OR ||; conditional ?; comma ,.
  • The end of a full declarator;
  • The end of a full expression: an initializer; the expression in an expression statement; the controlling expression of a selection statement (if or switch); the controlling expression of a while or do statement; each of the expressions of a for statement; the expression in a return statement.
  • Immediately before a library function returns.
  • After the actions associated with each formatted input/output function conversion specifier.
  • Immediately before and immediately after each call to a comparison function, and also between any call to a comparison function and any movement of the objects passed as arguments to that call.

关于自动和作用域的 C++ 初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9777561/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com