什么是“(void)new”是什么意思在C ++? [英] What does "(void) new" mean in C++?

查看:512
本文介绍了什么是“(void)new”是什么意思在C ++?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在看一个Qt 教程,它使用我以前没有见过的结构:

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()));

我试过这个没有(void)它仍然编译和工作,所以(void)

I've tried this without the (void) and it still compiles and works, so what is the purpose of the (void)?

推荐答案

将表达式转换为(void)基本上告诉编译器忽略该表达式的结果(计算后)。

Casting an expression to (void) basically tells the compiler to ignore the result of that expression (after computing it).

,每个表达式(每条语句/行)通过new操作符动态分配内存 - 并且由于new返回一个指针(地址)给存储器,通常的做法是将该指针存储在一个变量中,删除对象并释放内存。在你的例子中,由于指针被丢弃,显式转换(void)使程序员的意图清楚:我知道我在做什么 - 请丢弃新的返回值

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"

如果您对技术性感兴趣(引自C ++标准,第5条):

If you are interested in the technicalities (quoting from the C++ standard, clause 5):


可以显式转换为类型cv void。将忽略表达式值。 [注意:但是,如果值在一个临时变量(12.2)中,那个变量的析构函数直到通常时间才被执行,并且为了执行析构函数而保留变量的值。 - end note]

标量转换不适用于表达式的左值到值(4.1),数组到指针(4.2)和函数到指针(4.3) / p>

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.

如果你想知道这些对象如何被删除(如果确实他们被删除),答案是this QShortcut构造函数中的指针应该与new返回的值相同,并且可以传递给ShortcutManager。注意,构造函数中的'this'不同于传递给QShortcut构造函数的'this'指针。

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.

这篇关于什么是“(void)new”是什么意思在C ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆