Sub*_*iro 2 c++ setter constructor object-construction
问题与标题中的一样.
例如:
QPropertyAnimation *animation;
animation = new QPropertyAnimation(this, "windowOpacity", this);
Run Code Online (Sandbox Code Playgroud)
要么
QPropertyAnimation animation;
animation.setTargetObject(this);
animation.setPropertyName("windowOpacity");
animation.setParent(this);
Run Code Online (Sandbox Code Playgroud)
哪个更有效率?
编辑:虽然它没有显着差异,除非反复进行,我仍然想知道,我宁愿想要答案而不是意见 - 如stackoverflow的指导建议.
首先,为什么new在第一个例子中?我假设您将在同一存储(堆/堆栈)上创建两个变量.
其次,这不是Qt的问题,它一般适用于C++.
如果没有关于您正在创建的类的任何先验知识,您可以确定一件事:具有参数版本的构造函数至少与setter版本一样有效.
这是因为,在最坏的情况下,构造函数可能如下所示:
QPropertyAnimation(QObject* target, const QByteArray & prop_name, QObject* parent = 0)
{
// members are default initializer, now explicitly set
this->setTargetObject(target);
this->setPropertyName(prop_name);
this->setParent(parent)
}
Run Code Online (Sandbox Code Playgroud)
但是,任何至少通过一本好书的人都会像这样编写构造函数:
QPropertyAnimation(QObject* target, const QByteArray & prop_name, QObject* parent = 0)
: m_target(target)
, m_prop_name(prop_name)
, m_parent(parent)
{
// members explicitly initialized
}
Run Code Online (Sandbox Code Playgroud)