Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "(void) new" mean in C++?

Tags:

c++

void

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)?

like image 917
Skilldrick Avatar asked Jun 22 '09 22:06

Skilldrick


2 Answers

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.

like image 109
Faisal Vali Avatar answered Oct 08 '22 12:10

Faisal Vali


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".

like image 44
RichieHindle Avatar answered Oct 08 '22 13:10

RichieHindle