473,748 Members | 2,502 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

how to return std::vector from function?

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_p tr:

boost::shared_p tr< std::vector<int > > getV(){
boost::shared_p tr< std::vector<int > > v;
v->push_back(1) ;
v->push_back(2) ;
return v;
}

int main(){
boost::shared_p tr< 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_p tr<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
Mar 20 '06 #1
32 69689
zl2k wrote:
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(),
Why?
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.
Your description is correct, though that is not a memory leak.
Is there anyway that I can get a correct pointer from fun()? I also
thought to use a smart pointer, such as boost::shared_p tr:

boost::shared_p tr< std::vector<int > > getV(){
boost::shared_p tr< std::vector<int > > v;
v->push_back(1) ;
v->push_back(2) ;
return v;
}

int main(){
boost::shared_p tr< 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_p tr<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?


Instead of returning a vector, your function could simply take one by
reference.

void fun(std::vector <int>& v){
//fill the vector v;
}

int main(){
std::vector<int > a;
fun(a);
return 0;
}

Mar 20 '06 #2
> std::vector<int >* fun(){
//build a pointer to vector;
return *v;
do you mean

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.
It's not a memory leak, you have a pointer to an object on the stack
that's not there anymore.
Is there anyway that I can get a correct pointer from fun()?


you could do something like this...

std::vector<int >* fun()
{
std::vector<int > * v = new std::vector<int >();
//build *v;
return v;
}

and then make sure the caller deletes the returned value.

or you could do something like this...

void fun( std::vector<int > & v )
{
// build v;
}

int main()
{
std::vector<int > x;
fun(x);
}

-Brian

Mar 20 '06 #3
zl2k wrote :
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.
This is indeed the correct way to do it.

However, I believe there is a deep copy in fun(), so the
cost is big when the array is big.
There won't be any copy if the compiler is smart enough.
There are well known optimizations for return values to prevent
unnecessary copies.

Now I tried to return a pointer without
deep copy.


Using pointers here will only make it messy.
Mar 20 '06 #4

loufoque wrote:
zl2k wrote :
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.


This is indeed the correct way to do it.

However, I believe there is a deep copy in fun(), so the
cost is big when the array is big.


There won't be any copy if the compiler is smart enough.
There are well known optimizations for return values to prevent
unnecessary copies.

Now I tried to return a pointer without
deep copy.


Using pointers here will only make it messy.


That may be, but then if performance is an issue, you won't have to
assume that your compiler is smart enough to optimize. IMHO, passing
the array into the function in by reference makes the most since.

Mar 20 '06 #5
On Mon, 20 Mar 2006 18:44:34 +0100, Rolf Magnus wrote:
zl2k wrote:
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(),
Why?

I am not sure, correct me if not. Is there any deep copy needed if I
return a std container from a function? I'll be very happy if not.
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.
Your description is correct, though that is not a memory leak.

right, no leak but the returned pointer is 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_p tr:

boost::shared_p tr< std::vector<int > > getV(){ boost::shared_p tr<
std::vector<int > > v; v->push_back(1) ; v->push_back(2) ; return v;
}
}
int main(){
boost::shared_p tr< 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_p tr<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?


Instead of returning a vector, your function could simply take one by
reference.

void fun(std::vector <int>& v){
//fill the vector v;
}
}
int main(){
std::vector<int > a;
fun(a);
return 0;
}

In some cases, I can't construct an empty container and pass it to the
function. I want the class which owns the member function fun to own the
container. Say,

Class A {
public:
void GenerateBigData ();
void getBigData();
private:
std::vector<int > bigData;
}

Basically, the bigData is generated within the class A. When I need it, I
just want to access the bigData by calling getBigData. I don't want a
duplicated copy of the bigData, a reference will be good. I don't know how
to implement it.

zl2k
Mar 20 '06 #6
Hi!

zl2k <kd*******@gmai l.com>:
[...] In some cases, I can't construct an empty container and pass it to the
function. I want the class which owns the member function fun to own the
container. Say,

Class A {
public:
void GenerateBigData ();
void getBigData();
private:
std::vector<int > bigData;
}

Basically, the bigData is generated within the class A. When I need it, I
just want to access the bigData by calling getBigData. I don't want a
duplicated copy of the bigData, a reference will be good. I don't know how
to implement it.


If you find a reference acceptable, why not let getBigData return a const reference to bigData?

Regards,
Matthias
Mar 20 '06 #7
On 2006-03-20 12:35:39 -0500, zl2k <kd*******@gmai l.com> said:
Is there anyway that I can get a correct pointer from fun()? I also
thought to use a smart pointer, such as boost::shared_p tr:

boost::shared_p tr< std::vector<int > > getV(){
boost::shared_p tr< std::vector<int > > v;
v->push_back(1) ;
v->push_back(2) ;
return v;
}

int main(){
boost::shared_p tr< 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_p tr<T>::operator->() const [with T = std::vector<int ,
std::allocator< int> >]: Assertion `px != 0' failed.
Aborted


Your code is essentially right, save for one thing: You never set the
pointer to point at anything; i.e. it is a default constructed NULL
shared_ptr. Try this instead:

boost::shared_p tr< std::vector<int > > getV(){
//Note the 'new' on the next line, as it is what actually creates the vector
boost::shared_p tr< std::vector<int > > v = new std::vector<int >;
v->push_back(1) ;
v->push_back(2) ;
return v;
}

int main(){
boost::shared_p tr< std::vector<int > > v = getV();
std::cout << v->at(0);
return 0;
}

--
Clark S. Cox, III
cl*******@gmail .com

Mar 20 '06 #8
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.

#include <vector>

template <class T>
class Unconstructed
{
private:

union UniversalAllign ment
{
char a; int b; short c; long d;

bool e;

float f; double g; long double h;

void* p;
};

UniversalAllign ment buffer[
sizeof(T) / sizeof(Universa lAllignment)
+ static_cast<boo l>( sizeof(T) % sizeof(Universa lAllignment) )
];

public:

void* ObjectAddress()
{
return &buffer;
}

T& GetProperRefere nce()
{
return *static_cast<T* >( ObjectAddress() );
}

};

void fun(void* p)
{
new(p) std::vector<int >();
}
int main()
{
Unconstructed< std::vector<uns igned> > my_vec;

fun( my_vec.ObjectAd dress() );

std::vector<uns igned>& real_vec = my_vec.GetPrope rReference();

real_vec.push_b ack( 5 );

real_vec.~vecto r();
}
-Tomás
Mar 20 '06 #9
BigBrian a écrit :
That may be, but then if performance is an issue, you won't have to
assume that your compiler is smart enough to optimize.


If performance is an issue, use a performant compiler, that will indeed
optimize correctly.

It's a waste of time trying the write fast code with a compiler that
doesn't translate C/C++ code into the most efficient machine code it could.

Mar 20 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

18
2875
by: Janina Kramer | last post by:
hi ng, i'm working on a multiplayer game for a variable number of players and on the client side, i'm using a std::vector<CPlayer> to store informatik about the players. CPlayer is a class that contains another std::vector<CPosition>. Because one of the players is the client itself (and the size of the vector<CPlayer> doesn't change during a game), i thought i could store a std::vector<CPlayer>::iterator "localplayer" that points to the...
17
3355
by: Michael Hopkins | last post by:
Hi all I want to create a std::vector that goes from 1 to n instead of 0 to n-1. The only change this will have is in loops and when the vector returns positions of elements etc. I am calling this uovec at the moment (for Unit-Offset VECtor). I want the class to respond correctly to all usage of STL containers and algorithms so that it is a transparent replacement for std:vector. The options seems to be:
0
8987
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8826
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9534
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9366
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8239
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6793
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6073
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
3303
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2211
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.