سؤال

i'm not sure if i'm doing it correct or not hence asking this question ..
is reset function of boost::shared_ptr pointer can be used to initialize variable of type boost::shared_ptr<A>. Below is example code of wat i have done in my code :

struct A
{

};

struct B
{
   int x;
   std::string ss;

   boost::shared_ptr<A> A_ref; 

};

setdata(struct B *b)
{
   b->x=10;
   b->ss="hello";

   b->A_ref.reset(new A()); // initializing A_ref variable using reset function.
}

the above way of initializing A_ref variable good or does it have any other effect.

Thanks,

هل كانت مفيدة؟

المحلول 2

Yes this is the intended way to reset a shared pointer.

See http://en.cppreference.com/w/cpp/memory/shared_ptr/reset

Assignment is also supported, and has similar semantics.

b->A_ref = boost::make_shared<A>();

Make-shared is often preferred because

  • it can help getting exception safety in function calls with more than one shared pointer parameter
  • it can lead to more efficient memory representation of the reference counts

نصائح أخرى

You might use a constructor and/or a setter function to avoid the freestanding function:

#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>

struct A {};
struct B
{
   int x;
   std::string ss;
   boost::shared_ptr<A> A_ref;

   B()
   :    x(10), ss("hello"), A_ref(boost::make_shared<A>())
   {}

   void set();
};

void B::set() {
   x=10;
   ss="hello";
   A_ref = boost::make_shared<A>();
}

Note: make_shared is preferable (See the answer of @sehe).

Side note: You can replace setdata(struct B *b) by setdata(B *b) (omitting the needless struct here)

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top