13 Eylül 2017 Çarşamba

smart_ptr make_shared metodu

Giriş
Şu satırı dahil ederiz.
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
İmzası şöyledir.
namespace boost {
  template<typename T, typename Arg1>
  shared_ptr<T> make_shared( Arg1 const & arg1 );
}
Örnek - array
Şöyle yaparız.
#include "boost/smart_ptr/make_shared_array.hpp"
auto int_arr_ptr = boost::make_shared<int[]>(100);
Şöyle yaparız.
return boost::make_shared<uint8_t[]>(size);
Örnek - object
T ve Arg1 tipleri çağrı esnasında ayrı ayrı verilmelidir. Şu kod derlenmez.
int i = 10;
boost::shared_ptr<int> int_ptr = boost::make_shared(i); // doesn't work
Düzeltmek için şöyle yaparız.
boost::shared_ptr<int> int_ptr = boost::make_shared<int>(i);
T ve Arg1 tiplerinin ayrı ayrı verilebilmesi farklı tiplerin T ve Arg1 olarak kullanılabilmesini sağlar. Şöyle yaparız.
double d = 10.0;
std::shared_ptr<int> int_ptr = std::make_shared<int>(d);
Örnek  - object ve template
Parametre isteyen template için şöyle yaparız.
return boost::make_shared<Foo<Bar> >();
// in C++98, put space here      ^^^ 

Hiç yorum yok:

Yorum Gönder