初始化具有不确定值的对象

发布于 2024-12-21 12:15:22 字数 375 浏览 6 评论 0原文

以下是否会调用未定义的行为?

int x;
int i = x;

参考C++03

(4.1/1) 如果左值引用的对象不是 T 类型的对象 并且不是从 T 派生的类型的对象,或者如果该对象是 未初始化,需要此转换的程序已 未定义的行为。

编辑: 然而,从(3.3.1/1)开始,一个对象可以用它自己的不确定值初始化,为什么呢? IE

int x = x; //not an undefined behaviour

Does the following invoke undefined behavior?

int x;
int i = x;

Reference from C++03

(4.1/1) If the object to which the lvalue refers is not an object of type T
and is not an object of a type derived from T, or if the object is
uninitialized
, a program that necessitates this conversion has
undefined behavior.

Edit:
However, from (3.3.1/1) an object may be initialized with its own indetermine value, why is that? i.e.

int x = x; //not an undefined behaviour

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

把昨日还给我 2024-12-28 12:15:22

是的,因为您正在读取未初始化且未分配的变量 (x) 的值。

Yes, because you're reading the value of a variable (x) which was uninitialised and unassigned.

一瞬间的火花 2024-12-28 12:15:22

正如您的引用中所述,如果 x 未初始化,则它是未定义的。

int x; // 0 initialized
int i = x;

int main() {
  int z; // not initialized
  int k = z; // UB
}

It's undefined if x is uninitialized, as said in your quote.

int x; // 0 initialized
int i = x;

int main() {
  int z; // not initialized
  int k = z; // UB
}
沉默的熊 2024-12-28 12:15:22

唯一要记住的是,这没关系:

static int x;
int j = x;

但你的例子却不行。

The only thing to remember is that this is okay:

static int x;
int j = x;

but your example is not.

城歌 2024-12-28 12:15:22

它调用完美定义的行为。无论 x 在堆栈上分配时的垃圾值是什么,都将按原样分配给 i。

但是,根据您的编译器,您可能会收到有关引用未初始化变量的编译时警告。

It invokes perfectly defined behavior. Whatever garbage value x was when it is allocated on the stack will be assigned to i as is.

Depending on your compiler, however, you may get a compile time warning about referencing an uninitialized variable.

野鹿林 2024-12-28 12:15:22

int x = x; //不是未定义的行为

错误。

int x = x; //not an undefined behaviour

Wrong.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文