ST3
ST3

Reputation: 8946

c++ vector of boost::shared_ptr

I just started learning boost shared pointers.

I wrote a short program, results look good but I'm not sure if memory is deallocating well with my code. I would like to ask, if someone could look at my code and tell if I correctly use shared pointers.

#include <boost/shared_ptr.hpp>
#include <iostream>
#include <vector>
#include <string>

#define VECTSIZE 10

typedef boost::shared_ptr<std::string> StringPtr;
typedef std::vector<StringPtr> StringVect;

///////////////////////////////////////////////////////////////

std::string random_string (size_t length);

///////////////////////////////////////////////////////////////

int main()
{
    StringVect vect;

    for (int i = 0; i < VECTSIZE; i++)
    {
        std::string * stdstr;
        stdstr = new std::string;
        *stdstr = random_string(10);
        std::cout << *stdstr << "\r\n";

        StringPtr str(stdstr);
        vect.push_back(str);
    }

    std::cout << "\r\n\r\n";

    for (int i = 0; i < VECTSIZE; i++)
    {
        std::cout << *vect[i] << "\r\n";
    }

    vect.clear();
    system("pause");
    return 0;
}

///////////////////////////////////////////////////////////////

std::string random_string (size_t length)
{
    auto randchar = []() -> char
    {
        const char charset[] =
        "0123456789"
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        "abcdefghijklmnopqrstuvwxyz";
        const size_t max_index = (sizeof(charset) - 1);
        return charset[ rand() % max_index ];
    };

    std::string str(length,0);
    std::generate_n( str.begin(), length, randchar );
    return str;
}

Thanks for any advice; I hope it'll be helpful for me and others.

Upvotes: 2

Views: 6586

Answers (2)

Your use is correct in the sense that there are no direct memory leaks. However, you're not really exception safe - if random_string throws, you'll leak stdstr. It's better (and more idiomatic) to bypass rwa pointers entirely. Here's an example with using std::shared_ptr:

for (int i = 0; i < VECTSIZE; i++)
{
    StringPtr str = std::make_shared<std::string>();  // Encapsulates new
    *str = random_string(10);
    std::cout << *str << '\n'; //No \r here: text streams insert it on Windows automatically

    vect.push_back(str);
}

Also, as @ForEveR noted, there's little reason to allocate std::string dynamically in real world apps. But I assume you use it just as an excercise with smart pointers, which is fine of course.

Upvotes: 4

ForEveR
ForEveR

Reputation: 55887

All is okay, but you needn't vect.clear() string. However, string is value-type, don't use shared_ptr of string.

Upvotes: 3

Related Questions