Re: is there away for a function to return a struct?

  • From: < >
  • To:
  • Subject: Re: is there away for a function to return a struct?
  • Date: Wed, 27 Feb 2013 09:50:54 +0000 (GMT)

Hi

In plain C++ 98, you have two choices for something like this, return
by value or return by pointer. In return by value, the struct gets
copied. E.g.

struct X { int a; };

X makeX() {
   X x = { 1 };
   return x;
}

int main() {
  X x1 = makeX();
}

There is no worry as to who owns the X returned by makeX(), but if X is
big then this will be slow (all the work that is done to initialize x
has to be copied into x1).

Alternatively, by pointer

X* newX() {
  X* xp = new X();
  xp->a = 1;
  return xp;
}

int main() {
  X* xp1 = newX();
  delete xp1;
}

In this second case, you may want to consider smart pointers so that
you don't need to explicitly delete xp1. Which leads me to C++ 2011
which adds 'move semantics' which can avoid unnecessary copies. I don't
have much experience with that yet, so I'll stop there.

A+
Paul


is there away for a function to return a struct?

redawkin 02/27/2013

<Possible follow-up(s)>

Re: is there away for a function to return a struct?

paulf 02/27/2013

Project Features

About this Project

CND was started in November 2009, is owned by Leonid Lenyashin, and has 130 members.
By use of this website, you agree to the NetBeans Policies and Terms of Use (revision 20140418.2d69abc). © 2013, Oracle Corporation and/or its affiliates. Sponsored by Oracle logo
 
 
Close
loading
Please Confirm
Close