QIcon being reutilized during creation of QAction, is that possible?
-
The following code is part of my constructor
iconTitle = QIcon(":/a/a.png"); actionTitle = QString(tr("a")); _ActionOne = new QAction(iconTitle, actionTitle, this); iconTitle = QIcon(":/a/b.png"); actionTitle = QString(tr("b")); _ActionTwo = new QAction(iconTitle, actionTitle, this);I would like to know Why the code above works. I mean, the iconTitle is passed as reference and we change it. So all Actions refer to the same memory, right?
-
@ChrisW67
But isn't it an assignment operator instead of a copy constructor call?@leonardoMB
Here's my 2 cents, based on intuition & superstition :)When you pass the
const QIcon &toQActionit increments a reference count, for the icon, not theiconTitlevariable. ChangingiconTilleto (effectively "point to") a differentQIconwon't have any effect on, say, yourQActioncall. -
You pass the QIcon by const reference and the QAction constructor makes a copy. That copy is not connected to the original after that. The same thing is happening with the title text.
A copy is required because the QAction object has to control/ensure the lifetime of the icon it may providing for display. For example, you can call the constructor like this:
_ActionOne = new QAction(iconTitle, QIcon(":/a/a.png"), this);where the temporary QIcon has no existence beyond this statement, but the QAction must still function in a tool bar it is added to.
The Qt internals are designed to make such copies as efficient as they can be.
-
You pass the QIcon by const reference and the QAction constructor makes a copy. That copy is not connected to the original after that. The same thing is happening with the title text.
A copy is required because the QAction object has to control/ensure the lifetime of the icon it may providing for display. For example, you can call the constructor like this:
_ActionOne = new QAction(iconTitle, QIcon(":/a/a.png"), this);where the temporary QIcon has no existence beyond this statement, but the QAction must still function in a tool bar it is added to.
The Qt internals are designed to make such copies as efficient as they can be.
@ChrisW67
But isn't it an assignment operator instead of a copy constructor call? -
@ChrisW67
But isn't it an assignment operator instead of a copy constructor call?@leonardoMB
Here's my 2 cents, based on intuition & superstition :)When you pass the
const QIcon &toQActionit increments a reference count, for the icon, not theiconTitlevariable. ChangingiconTilleto (effectively "point to") a differentQIconwon't have any effect on, say, yourQActioncall. -
@leonardoMB
Here's my 2 cents, based on intuition & superstition :)When you pass the
const QIcon &toQActionit increments a reference count, for the icon, not theiconTitlevariable. ChangingiconTilleto (effectively "point to") a differentQIconwon't have any effect on, say, yourQActioncall.@JonB You are right, I understood it from the source code, right now and you reinforced it, thanks