引用您声明的同一变量
在使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从技术上讲,对象
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 ifint 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?没有错误或警告,因为它相当于:
就像
是一样 要
在同一语句中执行此操作,您需要使用构造函数,该构造函数不会编译:
就像:
不等于
There is no error or warning because its equivalent to:
Just like
is same as
To do this in the same statement you need to use constructor, which won't compile:
just like:
is not equivalent to