[英]Passing a unique pointer's pointer to a function that takes a double pointer
I have a function that effectively does this我有一个 function 可以有效地做到这一点
void foo(Class** c)
{
// memory checks and stuff
(*c) = new Class();
// more stuff
}
I cannot change this function.我无法更改此 function。 To call this function I have to do something like this.要调用这个 function 我必须做这样的事情。
Class* c = nullptr;
foo(&c);
if (c)
{
// stuff
}
delete c;
I would very much prefer to use a std::unique_ptr
rather than the raw pointer.我非常喜欢使用std::unique_ptr
而不是原始指针。 However, I don't know how to get the address of the internal pointer.但是,我不知道如何获取内部指针的地址。 The listing below does not compile, obviously, because I'm trying to take the address of an rvalue.显然,下面的清单无法编译,因为我正在尝试获取右值的地址。
std::unique_ptr<Class> c = nullptr;
foo(&(c.get()));
if (c)
{
// stuff
}
I realize I could make the raw pointer as well as the unique pointer, call the function, then give the raw pointer to the unique pointer, but I would prefer to not.我意识到我可以制作原始指针和唯一指针,调用 function,然后将原始指针提供给唯一指针,但我不想这样做。 Is there a way to do what I want to do?有没有办法做我想做的事?
Create a wrapper around foo
:在foo
周围创建一个包装器:
std::unique_ptr<Class> foo()
{
Class* c = nullptr;
foo(&c);
return std::unique_ptr<Class>(c);
}
Your hands are tied by the API of the function.你的双手被 function 的 API 绑住了。
The best solution I personally see is to do what you said you'd rather not: create the unique_ptr after calling the function.我个人认为最好的解决方案是做你说你不想做的事情:在调用 function 之后创建 unique_ptr。
If you call this function a lot or if you have many functions like it I would create a wrapper function that creates locally the raw pointer and returns unique_ptr.如果你经常调用这个 function,或者如果你有很多类似的函数,我会创建一个包装器 function,它在本地创建原始指针并返回 unique_ptr。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.