为什么可以将QObject *分配给QObject? [英] Why can I assign a QObject* to a QObject?
问题描述
考虑以下代码:
#include <QObject>
class A : public QObject
{
Q_OBJECT
public:
A(QObject* parent = 0) : QObject(parent) {}
}
int main()
{
A a = new A();
return 0;
}
为什么在编译器(或运行时)没有抱怨的情况下,将类型为A*
的对象分配给类型为A
的变量?
Why can I assign an object of type A*
to a variable of type A
without the compiler (or runtime) complaining?
推荐答案
在此代码中,A
的构造函数用于将A
类型的对象的 ,而不是分配它.通常,允许编译器隐式使用匹配的构造函数作为转换运算符,因此以下是合法代码:
In this code, the constructor of A
is used to convert an A*
to an object of type A
, instead of assigning it. In general the compiler is allowed to implicitly use a matching constructor as a conversion operator, so that the following is legal code:
struct B
{
B(int i){}
}
int main()
{
B b = 5;
return 0;
}
在问题代码中,由new
运算符产生的未命名A*
用作A
构造函数的parent
自变量.这是允许的,因为A
是从QObject
派生的(因此与参数列表匹配).但是,这显然是不希望的行为,因为a
不是new
返回的对象,而是该对象的父级A
类型的对象.
(此外,new
'ed对象永远不会delete
d,从而导致内存泄漏.)
In the code of the question, the unnamed A*
that results from the new
operator is used as the parent
argument of the constructor of A
. This is allowed since A
is derived from QObject
(and thus matches the argument list). However, this is clearly undesired behaviour because a
is not the object returned by new
, but an object of type A
parented to that object.
(In addition, the new
'ed object is never delete
d, resulting in a memory leak.)
为防止这种细微的错误,通常建议使QObject
派生的类的构造函数explicit
,以防止编译器将其误用作转换运算符. (这也适用于类似情况,不仅适用于Qt.)
使用以下修改后的代码,编译器将捕获该错误:
To prevent this kind of subtle error, it is generally advised to make the constructor of QObject
-derived classes explicit
to prevent the compiler from mis-using it as a conversion operator. (This applies to similar situations too, not only to Qt.)
With the following modified code, the compiler will catch the error:
class A : public QObject
{
Q_OBJECT
public:
explicit A(QObject* parent = 0) : QObject(parent) {}
}
这篇关于为什么可以将QObject *分配给QObject?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!