问题
I've been looking at a Qt tutorial which uses a construction I haven't seen before:
(void) new QShortcut(Qt::Key_Enter, this, SLOT(fire()));
(void) new QShortcut(Qt::Key_Return, this, SLOT(fire()));
(void) new QShortcut(Qt::CTRL + Qt::Key_Q, this, SLOT(close()));
I've tried this without the (void)
and it still compiles and works, so what is the purpose of the (void)
?
回答1:
Casting an expression to (void) basically tells the compiler to ignore the result of that expression (after computing it).
In your example, each of the expressions (per statement/line) is dynamically allocating memory via the new operator - and since new returns a pointer (address) to the memory, the usual practice is to store that pointer in a variable that you can use to eventually delete the object and deallocate the memory. In your example, since the pointer is being discarded, an explicit cast to (void) makes the intention of the programmer clear: "I know exactly what I am doing - please discard the value returned by new"
If you are interested in the technicalities (quoting from the C++ standard, clause 5):
Any expression can be explicitly converted to type cv void. The expression value is discarded. [ Note: however, if the value is in a temporary variable (12.2), the destructor for that variable is not executed until the usual time, and the value of the variable is preserved for the purpose of executing the destructor. —end note ]
The lvalue-to-rvalue (4.1), array-to-pointer (4.2), and function-to-pointer (4.3) standard conversions are not applied to the expression.
And if you are wondering how those objects are getting deleted (if indeed they are getting deleted), the answer is that the 'this' pointer within the constructor of QShortcut should have the same value as that returned by new, and that can be passed to a ShortcutManager. Note, the 'this' within the constructor is not the same as the 'this' pointer that is being passed to the constructor of QShortcut.
回答2:
Some C++ compilers will give a warning if you throw away the return value of a function like that. In this case, the code looks like it leaks memory, so you get a warning. The (void)
tells the compiler not to emit the warning: "Treat this function as though it returned void
".
回答3:
I think the reference returned from the new
statement isn't assigned to a pointer. I see that this
is being passed so QT must do something with that reference.
来源:https://stackoverflow.com/questions/1029743/what-does-void-new-mean-in-c