在此代碼中getDatabase
函數是第三方,我無法更改它。 main
函數裏面我用了shared_ptr
。所以有一個要求,我必須通過Database*
通過引用getDatabase
函數。我怎樣才能做到這一點?如何將引用傳遞給由std :: shared_ptr管理的指針
#include <iostream>
#include <memory>
class Database
{
};
void getDatabase(Database*& pDb)
{
pDb = createNewDatabase();
}
int main()
{
std::shared_ptr<Database> pDb=NULL;
getDatabase(pDb.get()); // Here is the issue pDb.get() doesn't do what I need
return 0;
}
爲什麼不先創建一個原始指針,調用API,然後在原始指針上構造智能指針? –
我知道可以有多種解決方法。但在這裏我想知道是否有一種直接的方式來傳遞引用由std :: shared_ptr管理的指針。希望你明白我的觀點 –
如果允許shared_ptr爲其嵌入的原始指針提供一個非const引用(左值),我們不會將其稱爲* smart *指針 –