我想傳遞一個指向一個函數的堆棧變量(我不控制),只需要一個boost::shared_ptr
。提升make_shared沒有模板參數
根據this answer,使用boost::make_shared
是要走的路。爲了測試這個功能,我寫了這個:
#include <iostream>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
int main(int argc, char const *argv[])
{
int i = 10;
boost::shared_ptr<int> int_ptr = boost::make_shared(i); // doesn't work
some_function(int_ptr); // this function takes only shared_ptr
return 0;
}
但它引發以下錯誤:如果我添加模板參數,像這樣它的工作原理,但究竟是什麼原因
error: no matching function for call to ‘make_shared(int&)’
boost::shared_ptr<int> int_ptr = boost::make_shared(i);
^
?
boost::shared_ptr<int> int_ptr = boost::make_shared<int>(i);
謝謝!
問問自己,如果你給它一個'int',函數應該使用什麼類型的共享指針。它如何知道你想要一個'shared_ptr'而不是'shared_ptr >',它也可以由'int'構造。 –
NathanOliver
請注意,模板參數推導不能包含有關結果將分配給的類型的信息。 'boost :: shared_ptr int_ptr ='部分不能被考慮來確定適當的模板參數。 –
當一個'shared_ptr'指向堆棧分配的內存時,如果它試圖刪除那個內存,將會是災難性的。 「我」是否需要通過指針來修改,還是需要「我」的副本? – chris