473,386 Members | 1,745 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

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_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>::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 69617
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_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>::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_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>::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*******@gmail.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*******@gmail.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_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>::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_ptr< std::vector<int> > getV(){
//Note the 'new' on the next line, as it is what actually creates the vector
boost::shared_ptr< std::vector<int> > v = new std::vector<int>;
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;
}

--
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 UniversalAllignment
{
char a; int b; short c; long d;

bool e;

float f; double g; long double h;

void* p;
};

UniversalAllignment buffer[
sizeof(T) / sizeof(UniversalAllignment)
+ static_cast<bool>( sizeof(T) % sizeof(UniversalAllignment) )
];

public:

void* ObjectAddress()
{
return &buffer;
}

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

};

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

fun( my_vec.ObjectAddress() );

std::vector<unsigned>& real_vec = my_vec.GetProperReference();

real_vec.push_back( 5 );

real_vec.~vector();
}
-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
On Mon, 20 Mar 2006 21:08:29 +0100, loufoque
<lo******@remove.gmail.com> wrote:
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.


What would you do with the returned temporary vector? Assign it to
another vector?

Regards,
Roland Pibinger
Mar 20 '06 #11

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


I disagree, especially in this case. Why return a huge object by value
and just hope the compiler does the optimization, when there are other
options that are just as easy to implement and then you *know* you
won't have this as a performance issue.

Also, using a different compiler isn't always an option.

-Brian

Mar 20 '06 #12
On Mon, 20 Mar 2006 09:55:01 -0800, BigBrian wrote:
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;
}

This has the same problem as mine: the v is lost after fun() is called and
the returned pointer is invalid.
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

This works but for some reason I can't transfer an empty vector to the fun
and before the fun is called.
Mar 20 '06 #13
On Mon, 20 Mar 2006 14:48:55 -0500, Clark S. Cox III wrote:
On 2006-03-20 12:35:39 -0500, zl2k <kd*******@gmail.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_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>::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_ptr< std::vector<int> > getV(){
//Note the 'new' on the next line, as it is what actually creates the vector
boost::shared_ptr< std::vector<int> > v = new std::vector<int>;
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;
}


It looks good, but can I sure that there is no deep copy involved when
getV() is called?

Mar 20 '06 #14
On Mon, 20 Mar 2006 20:33:00 +0100, Matthias Kluwe wrote:
Hi!

zl2k <kd*******@gmail.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


how to do that?
Mar 20 '06 #15
On Mon, 20 Mar 2006 12:32:48 -0800, BigBrian wrote:

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


I disagree, especially in this case. Why return a huge object by value
and just hope the compiler does the optimization, when there are other
options that are just as easy to implement and then you *know* you
won't have this as a performance issue.

Also, using a different compiler isn't always an option.

-Brian


So what is the straight forward way to solve the problem (without passing
an empty container into the fun and porpulize it inside)?
Mar 20 '06 #16
zl2k <kd*******@gmail.com> wrote:
On Mon, 20 Mar 2006 09:55:01 -0800, BigBrian wrote:
you could do something like this...

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


This has the same problem as mine: the v is lost after fun() is called and
the returned pointer is invalid.


Not quite. The v is lost after fun() is called, but the memory
pointed-to by v is still there and valid since it was allocated
dynamically on the heap, as opposed to on the stack. Then, returning a
pointer to this memory is OK, since it will exist longer than the
lifetime of fun().

--
Marcus Kwok
Mar 20 '06 #17
Marcus Kwok <ri******@gehennom.net.invalid> wrote:
zl2k <kd*******@gmail.com> wrote:
On Mon, 20 Mar 2006 09:55:01 -0800, BigBrian wrote:
you could do something like this...

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


This has the same problem as mine: the v is lost after fun() is called and
the returned pointer is invalid.


Not quite. The v is lost after fun() is called, but the memory
pointed-to by v is still there and valid since it was allocated
dynamically on the heap, as opposed to on the stack. Then, returning a
pointer to this memory is OK, since it will exist longer than the
lifetime of fun().


I should add that the caller of fun() is now responsible for deleting
the vector too.

--
Marcus Kwok
Mar 20 '06 #18
In article <pa****************************@gmail.com>,
zl2k <kd*******@gmail.com> wrote:
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.


Assuming that your code *really* can't make a copy of bigData then:

(best solution) Move the code that needs bigData into class A.

(next best) Have class A provide a const iterator to the beginning and
end of bigData.

class A {
vector<int> bigData;
void generateBigData(); // called from A's c_tor
public:
typedef vector<int>::const_iterator const_iterator;

A(): bigData() { generateBigData(); }

const_iterator begin() const { return bigData.begin(); }
const_iterator end() const { return bigData.end(); }
};

(next best) return a const reference to bigData.

class A {
vector< int > bigData;
public:
typedef vector< int > BigDataType;

const BigDataType& getBigData() const { return bigData; }
};

--
Magic depends on tradition and belief. It does not welcome observation,
nor does it profit by experiment. On the other hand, science is based
on experience; it is open to correction by observation and experiment.
Mar 20 '06 #19
Roland Pibinger a écrit :
What would you do with the returned temporary vector? Assign it to
another vector?


#include <iostream>

class Foo
{
public:
Foo()
{
std::cout << "Constructor of " << this << std::endl;
}

Foo(const Foo &foo)
{
std::cout << "Copying " << &foo << " to " << this << std::endl;
}

~Foo()
{
std::cout << "Destructor of " << this << std::endl;
}
};

Foo bar()
{
Foo foo;
/* whatever */
return foo;
}

int main()
{
Foo foo = bar();
}

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.

I know old compilers like MSVC6 only partially optimize that, copying it
once.

Mar 21 '06 #20
BigBrian a écrit :
Why return a huge object by value
and just hope the compiler does the optimization, when there are other
options that are just as easy to implement and then you *know* you
won't have this as a performance issue.


Because those options are ugly.
I recommend the elegant C++ way.
Mar 21 '06 #21
zl2k wrote:
On Mon, 20 Mar 2006 14:48:55 -0500, Clark S. Cox III wrote:
boost::shared_ptr< std::vector<int> > getV(){
//Note the 'new' on the next line, as it is what actually creates the vector
boost::shared_ptr< std::vector<int> > v = new std::vector<int>;
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;
}


It looks good, but can I sure that there is no deep copy involved when
getV() is called?


Yes. A boost::shared_ptr is, essentially, a pointer. So the the only
thing that is copied is the pointer, which holds some kind of reference,
to the vector.

Ben Pope
--
I'm not just a number. To many, I'm known as a string...
Mar 21 '06 #22

Tomás 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.

#include <vector>

template <class T>
class Unconstructed
{
private:

union UniversalAllignment
{
char a; int b; short c; long d;

bool e;

float f; double g; long double h;

void* p;
};

UniversalAllignment buffer[
sizeof(T) / sizeof(UniversalAllignment)
+ static_cast<bool>( sizeof(T) % sizeof(UniversalAllignment) )
];

public:

void* ObjectAddress()
{
return &buffer;
}

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

};

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

fun( my_vec.ObjectAddress() );

std::vector<unsigned>& real_vec = my_vec.GetProperReference();

real_vec.push_back( 5 );

real_vec.~vector();
}


Splendid. I think you have surpassed yourself. Pure, incomprehensible
genius. Well done :-)

To the OP: Don't ever write code like this if you want other people to
be able to work with it.

Gavin Deane

Mar 21 '06 #23
zl2k wrote:
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_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>::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 can't think of any.
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.


Then use a reference.

class A {
public:
void GenerateBigData();
const std::vector<int>& getBigData() const { return bigData; }
private:
std::vector<int> bigData;
};

int main()
{
A a;
a.GenerateBigData();
const std::vector<int>& data = a.getBigData();
}

Mar 21 '06 #24
zl2k wrote:
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_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>::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 can't think of any.
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.

Then use a reference.

class A {
public:
void GenerateBigData();
const std::vector<int>& getBigData() const { return
bigData; }
private:
std::vector<int> bigData;
};

int main()
{
A a;
a.GenerateBigData();
const std::vector<int>& data = a.getBigData();
}

Mar 21 '06 #25
On Tue, 21 Mar 2006 01:32:53 +0100, loufoque
<lo******@remove.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. But
with some compilers using some compiler switches under certain
non-portable circumstances one or even two function calls are just
elided.
RVO thwarts language rules and depends on questionable 'optimizations'
beyond the language. I wouldn't call that an 'elegant C++ way'. Quite
the contrary.

Best regards,
Roland Pibinger
Mar 21 '06 #26
Roland Pibinger a écrit :
RVO is a hack! According to C++ semantics copying is performed.
According to this [1], it is said in the specification that
implementations may optimize it.
The first form is already optimized by old pre-standard C++ compilers
like MSVC6.

[1] http://nkari.uw.hu/Tutorials/CPPTips/ret_val_opt

I actually searched it in the specification to be sure.
Unfortunetely I don't have the official one, so I used the current
working draft for the next version. (I probably wouldn't have the right
to paste the official anyway)
Here we go :

<bigquote>

When certain criteria are met, an implementation is allowed to omit the
copy construction of a class object, even if
the copy constructor and/or destructor for the object have side effects.
In such cases, the implementation treats the
source and target of the omitted copy operation as simply two different
ways of referring to the same object, and the
destruction of that object occurs at the later of the times when the two
objects would have been destroyed without the
optimization. This elision of copy operations is permitted in the
following circumstances (which may be combined
to eliminate multiple copies):

— in a return statement in a function with a class return type, when the
expression is the name of a non-volatile
automatic object with the same cv-unqualified type as the function
return type, the copy operation can be omitted
by constructing the automatic object directly into the function's return
value

— when a temporary class object that has not been bound to a reference
would be copied to a class object with
the same cv-unqualified type, the copy operation can be omitted by
constructing the temporary object directly into
the target of the omitted copy

[ Example:
class Thing {
public :
Thing ();
~ Thing ();
Thing ( const Thing &);
};

Thing f () {
Thing t;
return t;
}

Thing t2 = f();

Here the criteria for elision can be combined to eliminate two calls to
the copy constructor of class Thing: the copying
of the local automatic object t into the temporary object for the return
value of function f() and the copying of that
temporary object into object t2. Effectively, the construction of the
local object t can be viewed as directly initializing
the global object t2, and that object’s destruction will occur at
program exit. —end example ]

</bigquote>

But
with some compilers
Probably most of them.
Unfortunetely I only own two C++ compilers, gcc and icc to test it out
(it was optimized for both of them)
You are free to test it with all the C++ compilers you have.

using some compiler switches
using no switch.
The switch is to disable the optimization.

under certain
non-portable circumstances
The code I gave is always optimized whatever the platform and the
circumstances are with the compilers that perform such optimizations.
I wouldn't call that an 'elegant C++ way'. Quite
the contrary.


It is elegant because it doesn't use pointers which should be avoided
whenever possible. (they're pure evil)

Mar 21 '06 #27

zl2k wrote:
On Mon, 20 Mar 2006 12:32:48 -0800, BigBrian wrote:

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


I disagree, especially in this case. Why return a huge object by value
and just hope the compiler does the optimization, when there are other
options that are just as easy to implement and then you *know* you
won't have this as a performance issue.

Also, using a different compiler isn't always an option.

-Brian


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


Well, passing in a reference in a pretty straight forward way to do it.
Other option would be returning an auto_ptr<vector<X> >. This allows
you to create a vector on the heap but still not worry about who needs
to destroy it.

Mar 21 '06 #28
loufoque wrote:
BigBrian a écrit :
Why return a huge object by value
and just hope the compiler does the optimization, when there are
other options that are just as easy to implement and then you *know*
you won't have this as a performance issue.


Because those options are ugly.
I recommend the elegant C++ way.


I second that. And besides, C++0x "rvalue reference" proposal will make the
elegant C++ way have the optimal performance regardless of compiler
optimizations.
Mar 22 '06 #29
Roland Pibinger wrote:
On Tue, 21 Mar 2006 01:32:53 +0100, loufoque
<lo******@remove.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 #30
Roland Pibinger wrote:
On Tue, 21 Mar 2006 01:32:53 +0100, loufoque
<lo******@remove.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::ostream &out){
push_back( 7 );
std::ifstream fin( "graphic.txt" ); // JoeC's file, numbers in
text.
if( fin ){
for( int nud(0); fin >> nud; ){ push_back( nud );}
}
else{ out<<"could not open file"<<std::endl;}
} // VecInt Ctor
// ------------------------------------
void fun(){ at( 0 ) = 99; return;}
// void fun(size_t index){ if(index<size()) at( index ) = 99;}
// ------------------------------------
void Write(std::ostream &out = std::cout){
for(const_iterator 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
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...
17
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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,...
0
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...
0
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,...
0
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...

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.