Boost logo

Boost Users :

Subject: [Boost-users] Problem with list_of, make_shared and shared_ptr
From: alapex0310_at_[hidden]
Date: 2010-07-23 10:06:00


I am using boost::list_of to pass a vector of pairs of string +
"unsigned char" to SomeClass (as it can be seen in the typedef below -
keys_t). This passes the whole vector to SomeClass which copies the
vector in the keys_ private variable. The problem is: the copy ctor now
copies the full vector in each SomeClass. To prevent this, as you can
see, I have defined another data member which is a reference to const
keys_t in my class and am initializing it in the member initialization
list of the constructor with the value of keys_ and having the copy
constructor copy just the reference of keys_ (rkeys_, that is - as you
can see in the member initialization list of the copy ctor) instead of
the full vector but the new SomeClass then holds an uninitialized vector
(keys_) which is ugly and I hate seeing it in the class. Can I possible
use Boost::make_shared with boost::list_of to return me a pointer to
whatever (vector of type keys_t) boost::list_of returns and store that
pointer instead in my class (e.g. keys_t typedef then reflects
boost::shared_ptr instead of a traditional pointer) instead of the full
vector. Specifying the arbitrary constants (apparently using
boost::list_of) right in the constructor call is a requirement. Is there
any way I can do it? Of course, I guess I could use boost::make_shared
to return me a boost::shared_ptr to keys_t but my code is not even
compiling and giving me errors in boost headers:

std::vector<std::pair<std::string,unsigned char>> keys_t;

class SomeClass
     SomeClass(std::string nameStr, keys_t keys) : keys_(keys),
       rkeys_(keys_) {}
     SomeClass(const SomeClass &koa) : rkeys_(koa.keys_) {}

              keys_t keys_;
     const keys_t &rkeys_;


SomeClass *psc = new SomeClass( "MyClass",
list_of<pair<string,unsigned char>>
                             ("one", 1)
                             ("two", 2)
                             ("three", 3)
                             ("four", 4)
                             ("five", 5)
                             ("six", 6));

I read in boost::doc that I cannot pass shared_ptr directly as a
function argument because of temporary problems. So, I cannot pass a
shared_ptr to the constructor of SomeClass and that's the primary reason
I hope if you can help me use make_shared or something similar to get
the job done. The constraint is: I *must* pass the arbitrary number of
pairs of string-unsigned-char in my constructor and that's why I am
using list_of. Any way out?


Boost-users list run by williamkempf at, kalb at, bjorn.karlsson at, gregod at, wekempf at