I need to create a function that returns an allocated shared_ptr variable. is this the correct way?
typedef boost::shared_ptr<std::vector<char> > sharePtr;
void createPtr(sharePtr &p)
{
开发者_如何转开发p = sharePtr(new std::vector<char>);
}
void test()
{
sharePtr p;
createPtr(p);
}
Yes, it is correct. But why not write just:
sharedPtr createPtr()
{
return sharePtr(new std::vector<char>);
}
void test()
{
sharePtr p = createPtr();
}
? This can be faster than your version, and faster even more with a compiler supporting move semantics.
It's also recommended to use make_shared
instead of direct new
:
sharedPtr createPtr()
{
return make_shared<std::vector<char>>();
}
because it can avoid the memory allocation for the reference counter.
精彩评论