Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/security/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 将智能指针传递给引用指针参数的函数_C++_Smart Pointers - Fatal编程技术网

C++ 将智能指针传递给引用指针参数的函数

C++ 将智能指针传递给引用指针参数的函数,c++,smart-pointers,C++,Smart Pointers,如何将对指针的引用作为参数传递给函数 smart_ptr<T> val; // I have this smart pointer // And I want to pass it to this function, so that this function will fill the smart pointer with proper value void Foo(T*& sth) { sth = memoryAddress; } smart_ptr val;

如何将对指针的引用作为参数传递给函数

smart_ptr<T> val; // I have this smart pointer

// And I want to pass it to this function, so that this function will fill the smart pointer with proper value
void Foo(T*& sth)
{
    sth = memoryAddress;
}
smart_ptr val;//我有这个智能指针
//我想把它传递给这个函数,这样这个函数就可以用正确的值填充智能指针
无效Foo(T*&sth)
{
记忆地址;
}
编辑
现在我明白了。谢谢大家的回答

你不能那样做。您可以使用“
T*raw=val.get()
”然后“
Foo(raw)
”传递原始指针,但不能像
Foo
中那样设置
shared\u ptr
的原始指针。如果希望
Foo
设置
shared_ptr
,请将其设置为非常量
shared_ptr
参考

像这样:

template<typename T>
Foo(shared_ptr<T>& ptr)
{
    ptr.reset(memoryAddress); // Or assign it, or make_shared, or whatever.
}

shared_ptr<int> intptr;
Foo(intptr);
模板
Foo(共享的ptr和ptr)
{
ptr.reset(memoryAddress);//或者分配它,或者使_共享,或者其他什么。
}
共享ptr intptr;
Foo(intptr);
或者更好的方法是,让
Foo
返回一个
共享的ptr
,而不是通过引用来获取它。

啊,这个API太难看了

我将假设函数承诺它“返回”的指针拥有一个资源,调用者将以
smart\u ptr
的方式删除该资源,并且
smart\u ptr
可以从任意指针初始化。否则就做不到

您可以像在没有智能指针的情况下一样抓取指针,然后将其放入智能指针中

T* ptr;
Foo(ptr);
smart_ptr<T> val(ptr);
如果函数没有获得资源的所有权,那么所需要的只是能够使用任意指针重新初始化

//smart_ptr<T> val;
T* ptr = val.get();
Foo(ptr);
val.reset(ptr);
//smart\u ptr val;
T*ptr=val.get();
Foo(ptr);
重置值(ptr);

简单的答案是你不能。而智能指针 几乎可以肯定的是,在内部的某个地方包含了一个
T*
,smart 指针强制执行各种不变量,其中许多不变量可以是 如果您可以在不通过的情况下更改此指针,则会发生断开 用户界面。唯一的解决方案是调用函数 使用原始指针,然后使用原始指针进行初始化 智能指针,前提是您确定指针 您得到的数据满足智能指针的要求(例如。
new
操作员分配)

您的意思是:
shared\u ptr
?我想首先确保返回的指针满足智能指针的要求。有能力设计这样一个破界面的人也能使用
malloc
@James是的,这正是我第二段的第一个假设。我明白了。关于函数如何处理entry中的参数的一点也是很好的。通常,这样的函数不会做任何事情,但您永远不会知道。
Foo(val.get())
不应该编译。如果是的话,你的编译器就坏了。你说得对。不过,如果你通过一个临时途径,它是有效的。我会更新我的答案。如果他能将界面更改为
Foo
,他还不如做对,让
Foo
\返回一个指针。这就是我说的:)
//smart_ptr<T> val;
T* ptr = val.get();
Foo(ptr);
val.reset(ptr);