引用您声明的同一变量

发布于 2024-12-09 03:26:22 字数 239 浏览 0 评论 0原文

在使用 C++ 代码时,我多次看到以下类型错误:

QString str = str.toUpper();

这可能是一个相当容易犯的错误,但它可以编译和执行(有时会崩溃,有时不会)。我看不出在什么情况下你会真正想做这件事。

一些测试表明,复制构造函数被调用,而不是默认的构造函数,并且对象是从复制构造函数内部给出的。

谁能解释为什么这不是编译器错误,甚至不是警告?

I've seen the following type mistake a couple of times while working with C++ code:

QString str = str.toUpper();

This can be a fairly easy mistake to make and yet it compiles and executes (sometimes with crashes, sometimes without). I can't see any circumstances under which it would be something that you'd actually want to do.

Some testing has revealed that the copy constructor is invoked, not the default one, and that the object is being given itself from within the copy constructor.

Can anyone explain why this isn't a compiler error, or even a warning?

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

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

发布评论

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

评论(2

表情可笑 2024-12-16 03:26:22

从技术上讲,对象 str 是在到达等号时定义的,因此可以在此时使用它。

错误在于尝试用对象本身初始化对象,并且编译器可以对此发出警告(如果它能够检测到它)。然而,由于并非在所有情况下都可以进行检测,因此不需要编译器。

例如,如果 int f(const int&) 不使用其参数的值,则 int x = f(x); 是完全正确的。如果编译器还没有看到函数体,它如何知道这一点?

Technically the object str is defined when you reach the equal sign, so it can be used at that point.

The error is in trying to initialize the object with itself, and the compiler is allowed to warn about that (if it is able to detect it). However, as the detection is not possible in every case, the compiler is not required.

For example int x = f(x); is entirely correct if int f(const int&) doesn't use the value of its parameter. How is the compiler to know that if it hasn't seen the function body yet?

征﹌骨岁月お 2024-12-16 03:26:22

没有错误或警告,因为它相当于:

QString str;
str = str.toUpper();

就像

QString str = "aaa";

是一样 要

QString str;
str = "aaa";

在同一语句中执行此操作,您需要使用构造函数,该构造函数不会编译:

QString str(str.toUpper());

就像:

QString str("aaa");

不等于

QString str;
str = "aaa";

There is no error or warning because its equivalent to:

QString str;
str = str.toUpper();

Just like

QString str = "aaa";

is same as

QString str;
str = "aaa";

To do this in the same statement you need to use constructor, which won't compile:

QString str(str.toUpper());

just like:

QString str("aaa");

is not equivalent to

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