将智能指针传递给参考指针参数的函数

use*_*932 3 c++ smart-pointers

如何将智能ptr传递给参考指针作为参数的函数?

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;
}
Run Code Online (Sandbox Code Playgroud)

编辑现在我明白了.谢谢大家的所有答案!

Jam*_*nze 7

简单的答案是你做不到.虽然智能指针几乎肯定在T*内部包含某个地方,但智能指针强制执行各种不变量,如果您可以在不通过用户界面的情况下更改此指针,则许多不变量可能会被破坏.唯一的解决方法是调用与原始指针的函数,然后使用原始指针初始化智能指针,提供你是确保你得到的指针满足智能指针的要求(例如,通过分配的new运营商) .