如何查找auto_ptr的地址

How to find the address of an auto_ptr

本文关键字:ptr 地址 auto 何查找 查找      更新时间:2023-10-16

我有一个函数,它接受unsigned char**作为参数。我想传递一个使用auto_ptr定义的参数内存。我正在尝试这样的代码:

std::auto_ptr<unsigned char> pImageBuffer; func(&(pImageBuffer.get()));

但是,看起来我在这里做错了什么。我得到一个错误说:

Cannot take the address of an rvalue of type 'element_type *' (aka 'unsigned char *')

你知道我该怎么做吗?我不能使用unique_ptr或更改函数的签名。

听起来,传递指针地址的函数需要修改所指向的地址(而不是底层对象)。您不能直接通过auto_ptr执行此操作(您试图获取auto_ptr::get的返回值的地址——这是非法的,因为它是rvalue)。您需要先创建一个临时变量来保存原始指针。我推荐这个:

unsigned char* tmpPtr;
func(&tmpPtr);
std::auto_ptr<unsigned char> pImageBuffer(tmpPtr);

当然,这是假设函数希望您拥有它将tmpPtr设置为指向的东西的所有权