how to use shared_ptr to wrap std::vector and return from function?

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

how to use shared_ptr to wrap std::vector and return from function?

kdsfinger
hi, Boost users

Suppose I created a large data in a function and want to return it back to where the function was called. I want to return the pointer so that the deep copy of the large data is not needed and memory leak is nicely handled. Can someone let me know how to do it? Here is something come up in my mind:

 boost::shared_ptr< std::vector<int> > getV(){
 boost::shared_ptr< std::vector<int> > v;
 v->push_back(1);
 v->push_back(2);
// bla bla bla
 return v;
 }
 
 int main(){
 boost::shared_ptr< std::vector<int> > v = getV();
 std::cout << v->at(0);
 return 0;
 }
 
 I got the following message when run the program:
 /usr/include/boost/shared_ptr.hpp:253: T*
 boost::shared_ptr<T>::operator->() const [with T = std::vector<int,
 std::allocator<int> >]: Assertion `px != 0' failed. Aborted
 
 How can I get it correct? Is there any deep copy when the getV() return
 the shared_ptr?

Thanks a lot.

zl2k

_______________________________________________
Boost-users mailing list
[hidden email]
http://lists.boost.org/mailman/listinfo.cgi/boost-users
Reply | Threaded
Open this post in threaded view
|

Re: how to use shared_ptr to wrap std::vector and return from function?

Thomas Matelich
On 3/20/06, [hidden email] <[hidden email]> wrote:
>   boost::shared_ptr< std::vector<int> > getV(){
>   boost::shared_ptr< std::vector<int> > v;
>   v->push_back(1);
>   v->push_back(2);
>  // bla bla bla
>   return v;
>   }

you forgot to create a vector for v.

either:
boost::shared_ptr<std::vector<int> > v(new std::vector<int>);
or:
v.reset(new std::vector<int>);

oughtta do it.
_______________________________________________
Boost-users mailing list
[hidden email]
http://lists.boost.org/mailman/listinfo.cgi/boost-users