struct POD and return-by-value

H

Hicham Mouline

Hello,

struct S {
bool b1;
bool b2;
bool b3;
};

Is there a difference between

S f()
{
const S s = {true, false, false};
return s;
}

and

S f()
{
S s;
s.b1 = true;
s.b2 = false;
s.b3 = false;
return s;
}


currently,
S f()
{
return {true, false, false};
}
is not allowed. is this gonna change in c++0/1x ?

regards,
 
M

Maxim Yegorushkin

Hello,

struct S {
  bool b1;
  bool b2;
  bool b3;
};

Is there a difference between

S f()
{
  const S s = {true, false, false};
  return s;
}

and

S f()
{
  S s;
  s.b1 = true;
  s.b2 = false;
  s.b3 = false;
  return s;
}

There is no difference if the members of S do not have user defined
constructors (i.e. S is POD).

If they do (i.e. S is not POD), however, the second form ends up first
calling the default constructors for members and then the assignment
operators (i.e. the same consideration as with initialiser lists vs.
initialising in the constructor body block).
currently,
S f()
{
  return {true, false, false};}

is not allowed. is this gonna change in c++0/1x ?

It is. http://en.wikipedia.org/wiki/C_0x#Initializer_lists
 
V

Victor Bazarov

Hicham said:
struct S {
bool b1;
bool b2;
bool b3;
};

Is there a difference between

S f()
{
const S s = {true, false, false};
return s;
}

and

S f()
{
S s;
s.b1 = true;
s.b2 = false;
s.b3 = false;
return s;
}

Not really. Initialization should be preferred over assignment, but in
your case it most likely does not matter.
currently,
S f()
{
return {true, false, false};
}
is not allowed. is this gonna change in c++0/1x ?

I don't know. But why bother? The former solution (with a const S)
should work just fine, no?

V
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,043
Latest member
CannalabsCBDReview

Latest Threads

Top