c++ - 将对象指针转换为双 void 指针(指向 void 指针的指针)

标签 c++ pointers casting type-conversion pointer-to-pointer

我在库中有一个类方法(无法更改它),它采用双空指针作为其参数之一。声明如下:

bool Queue::pop(void **packet, int &size, unsigned short &sn)

在我的应用程序代码中,我想将此函数传递给另一种对象的指针,在本例中为 GstBuffer指针类型。如果我将指针转换为 (void**) ,如下面的代码片段所示,我似乎可以在没有任何编译器错误的情况下执行此操作,但我怀疑这是否会导致正确的行为。像这样转换指针是否有效?

guint16 sn;
int size;
GstBuffer *buf; 
Queue *Q = ... // create a Queue instance
Q->pop((void **)&buf, size, sn);  // is this conversion valid?
size = gst_buffer_get_size(buf);

最佳答案

出于所有意图和目的,void 指针可以保存任何对象(数据类型)的地址,它可以指向任何对象,并且可以类型转换为任何对象,您的代码是有效的,我将使用更惯用的转换:

Q->pop(reinterpret_cast<void**>(&buf), size, sn);

§7.3.12 指针转换 [conv.ptr]

  1. A prvalue of type “pointer to cv T”, where T is an object type, can be converted to a prvalue of type “pointer to cv void”. The pointer value (6.8.3) is unchanged by this conversion.

Example:

void example(void **packet){
    std::cout << *packet << "\n";                   // pointer value
    std::cout << packet << "\n";                    // pointer address
    std::cout << **reinterpret_cast<int**>(packet); // value
}

int main() 
{
    int* x = new int(20);
    std::cout << x << "\n";                         // pointer value
    std::cout << &x << "\n";                        // pointer address
    example(reinterpret_cast<void**>(&x));       
    delete x;
}

输出:

0xb83eb0
0x7ffc181ab2c8
0xb83eb0
0x7ffc181ab2c8
20

甚至只需要显式转换,因为它是指向指针的指针,否则转换将是隐式的,不需要转换。

关于c++ - 将对象指针转换为双 void 指针(指向 void 指针的指针),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67313767/

相关文章:

C - 将 execvp 与用户输入一起使用

c - 是否可以更改 const 全局变量的值?

java - Java中ClassCastException的解释

c++ - 如何使用 rapidjson 库从 vector<string> 数据创建 json 文件?

c++ - 是否可以在不子类化的情况下使用 QThread 实现轮询?

c++ - 使用命令行将二维数组传递给 C++

c# - 通过 mono 命令执行时出现异常

c++ - 函数/方法如何返回对对象的引用在内部工作

java - 将对象列表转换为接口(interface)列表时出错

objective-c - 在 Objective-C 中,Java 的 "instanceof"关键字的等价物是什么?