Z
zl2k
hi, c++ user
Suppose I constructed a large array and put it in the std::vector in a
function and now I want to return it back to where the function is called.
I can do like this:
std::vector<int> fun(){
//build the vector v;
return v;
}
int main(){
std::vector<int> a = fun();
return 0;
}
It works fine. However, I believe there is a deep copy in fun(), so the
cost is big when the array is big. Now I tried to return a pointer without
deep copy.
std::vector<int>* fun(){
//build a pointer to vector;
return *v;
}
int main(){
std::vector<int>* a = fun();
return 0;
}
This got memory leak trouble in fun() since v will be deleted after return
thus the pointer returned will be invalid.
Is there anyway that I can get a correct pointer from fun()? I also
thought to use a smart pointer, such as boost::shared_ptr:
boost::shared_ptr< std::vector<int> > getV(){
boost::shared_ptr< std::vector<int> > v;
v->push_back(1);
v->push_back(2);
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>:perator->() 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
Suppose I constructed a large array and put it in the std::vector in a
function and now I want to return it back to where the function is called.
I can do like this:
std::vector<int> fun(){
//build the vector v;
return v;
}
int main(){
std::vector<int> a = fun();
return 0;
}
It works fine. However, I believe there is a deep copy in fun(), so the
cost is big when the array is big. Now I tried to return a pointer without
deep copy.
std::vector<int>* fun(){
//build a pointer to vector;
return *v;
}
int main(){
std::vector<int>* a = fun();
return 0;
}
This got memory leak trouble in fun() since v will be deleted after return
thus the pointer returned will be invalid.
Is there anyway that I can get a correct pointer from fun()? I also
thought to use a smart pointer, such as boost::shared_ptr:
boost::shared_ptr< std::vector<int> > getV(){
boost::shared_ptr< std::vector<int> > v;
v->push_back(1);
v->push_back(2);
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>:perator->() 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