473,854 Members | 1,665 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
32 69721
Roland Pibinger wrote:
On Tue, 21 Mar 2006 01:32:53 +0100, loufoque
<lo******@remov e.gmail.com> wrote:
If you compile this with gcc in normal mode, you can see there is no
copying done. (you can disable those optimizations in gcc with
-fno-elide-constructors, and you will therefore see that it is copied
twice) Other modern compilers probably do so too.
RVO is a hack! According to C++ semantics copying is performed.


According to the C++ standard, copying may be performed, but doesn't need
to. This is an option.
But with some compilers
probably most nowadays and even older ones
using some compiler switches
probably even without them or with standard optimization switches.
under certain non-portable circumstances
? What's unportable about those circumstances?
one or even two function calls are just elided.
No. The returned object is just not copied but used directly. This means
that no additional storage is acquired, no copy of the object is made
(which includes but isn't limited to eliding the copy constructor), and of
course only one object is destroyed instead of two. So it's much more than
just eliding a function call or two.
RVO thwarts language rules and depends on questionable 'optimizations'
beyond the language.
It's not at all beyond the language. It's part of it.
I wouldn't call that an 'elegant C++ way'. Quite the contrary.


void func1(const MyClass& obj);
MyClass func2();

func1(func2());

looks more elegant to me than:

void func1(const MyClass& obj);
void func2(MyClass& obj);

MyClass x;
func2(x);
func1(x);

and if you consider operators, you don't even have any choice:

MyClass operator+(const MyClass& lhs, const MyClass& rhs);

Would you instead prefer this?

void add(MyClass& result, const MyClass& lhs, const MyClass& rhs);

Which one looks more like an "elegant C++ way" to you?

Mar 22 '06 #31

zl2k wrote in message ...

So what is the straight forward way to solve the problem (without passing
an empty container into the fun and porpulize it inside)?


If you can't take the vector to fun(), put fun() in the vector!! <G>

#include <iostream> // C++
#include <ostream> // std::endl
#include <fstream>
#include <vector>

class VecInt : public std::vector<int > { public:
VecInt(std::ost ream &out){
push_back( 7 );
std::ifstream fin( "graphic.tx t" ); // JoeC's file, numbers in
text.
if( fin ){
for( int nud(0); fin >> nud; ){ push_back( nud );}
}
else{ out<<"could not open file"<<std::end l;}
} // VecInt Ctor
// ------------------------------------
void fun(){ at( 0 ) = 99; return;}
// void fun(size_t index){ if(index<size() ) at( index ) = 99;}
// ------------------------------------
void Write(std::ostr eam &out = std::cout){
for(const_itera tor w = begin(); w != end(); ++w)
out<< *w <<" "; // out << *w << std::endl;
out<<std::endl;
} //Write(ostream&)
private:
// stuff here
}; //class VecInt
// ------------------------------------

int main(){
VecInt Vec1( std::cout );
Vec1.push_back( 77777 );
Vec1.Write( std::cout );
Vec1.fun();
std::ofstream fout( "Afile.txt" );
if( fout ){
Vec1.Write( fout );
}
return 0;
} // main()end

[ throw (std::exception )'s removed ]
[ tested on GCC MinGW 3.3.1. corrections welcome ]
--
Bob R
POVrookie
Mar 23 '06 #32

zl2k skrev:
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.
I would be quite surprised to see a compiler having any deep copy here.
[snip] Thanks a lot.

zl2k


The only sensible thing to do is follow your original hunch and let the
optimizer do the job for you. If you decide that your program is to
slow and if your profiling shows the copy to be the culprit, by all
means return here (or even better to a group dedicated to your
compiler) for more advice.
Until then just don't throw away the way that is most readable and also
probably the fastest in order to replace it with an obscure, slow
algorithm.

Mar 23 '06 #33

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

Similar topics

18
2892
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
3369
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
9901
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
10684
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...
1
10763
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10371
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9517
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
7918
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
5942
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4159
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3188
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.