开发者

allocate shared_ptr in a function

开发者 https://www.devze.com 2023-01-29 01:35 出处:网络
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;

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消