I'm building a MyString class that has a `split' member function which should return a list of matches based on the argument given. To represent the list I am using the container std::vector<std::string>. The question is how to return this in a nice way. My first try loooked like this:
Code:
#include <iostream>
#include <string>
#include <vector>
namespace tut {
using std::vector;
using std::string;
class MyString {
private:
string data;
public:
MyString(string str) : data(str) {}
vector<string> *split(string regexp) {
(void)regexp; // ignore for now
vector<string> *vec = new vector<string>;
// Push some example elements
vec->push_back("one");
vec->push_back("two");
vec->push_back("three");
return vec;
}
};
}
int main()
{
using namespace std;
using namespace tut;
{
vector<string> *list = MyString("one, two, three").split(", ?");
vector<string>::iterator it;
for (it = list->begin(); it != list->end(); it++) {
cout << *it << endl;
}
delete list;
}
/* ... */
}
The idea is that list should be deallocated at the point /* ... */ is reached. As you can see, manually deleting list is required. Then I thought to use a smart pointers as follows:
Code:
namespace tut {
using std::vector;
using std::string;
using std::shared_ptr;
typedef shared_ptr<vector<string> > strvec_ptr;
class MyString {
private:
string data;
public:
MyString(string str) : data(str) {}
strvec_ptr split(string regexp) {
(void)regexp; // ignore for now
strvec_ptr vec (new vector<string>);
// Push some example elements
vec->push_back("one");
vec->push_back("two");
vec->push_back("three");
return vec;
}
};
}
Now the user of the class can use a strvec_ptr for the list, and the list should be freed automatically when it goes out of scope.
Code:
{
strvec_ptr list = MyString("one, two, three").split(", ?");
vector<string>::iterator it;
for (it = list->begin(); it != list->end(); it++) {
cout << *it << endl;
}
}
/* ... */
Question 1: is this correct use of the shared_ptr?
Question 2: Is there a better alternative I am overlooking?