Tal
Tal

Reputation: 55

allocate shared_ptr in a function

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);
}

Upvotes: 3

Views: 3674

Answers (1)

Yakov Galka
Yakov Galka

Reputation: 72479

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.

Upvotes: 5

Related Questions