5

One can create an anonymous object that is initialized through constructor parameters, such as in the return statement, below.

struct S {
  S(int i_, int j_) : i(i_), j(j_) { }
  int i, j;
};

S f()
{
  return S(52, 100);
}

int main()
{
  cout << f().i << endl;
  return 0;
}

However, can one similarly create an anonymous aggregate that is initialized with a brace initializer? For example, can one collapse the body of f(), below, down to a single return statement without an "s?"

struct S {
  int i, j;
};

S f()
{
  S s = { 52, 100 };
  return s;
}

int main()
{
  cout << f().i << endl;
  return 0;
}
Shog9
  • 156,901
  • 35
  • 231
  • 235
plong
  • 1,723
  • 3
  • 14
  • 14

3 Answers3

8

You can't in the current version of C++. You will be able to in C++ 0x -- I believe anyway. Of course, it's still open to revision -- at one time I believed you'd be able to specify concepts in C++ 0x, but that's gone...

Edit: The reference would be [dcl.init] (§8.5/1) in N2960. The most relevant bit is the definition of 'braced-init-list' in the BNF (and the last bit of text, saying that the initialization described in that section can/does apply to return values).

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
  • +1 @Jerry. Right, but it is in §8.5.4/1. You missed a number. – Fernando N. Oct 21 '09 at 17:02
  • §8.5/1 was the part I was looking at (and gives enough to answer the current question). You're right, however, that §8.5.4/1 is what covers braced initializer lists specifically, and it has a lot more detail about them. – Jerry Coffin Oct 21 '09 at 17:11
5

Not in C++. But you can in C99, using so-called compound literals:

struct S {
  int i, j;
};

struct S F()
{
  // Valid C99, invalid C++:
  return (struct S){ 52, 100 };
}

[C99: §6.5.2, 6.5.2.5]
[C++98: §5.2.3, 8.5, 12.1, 12.2]

Some C++ compilers provide this as an extension, but it's not legal ISO C++98. For example, g++ will accept this code by default, but if you compile with the -pedantic option, it will reject it.

Adam Rosenfield
  • 390,455
  • 97
  • 512
  • 589
1

You will be able to use brace initialization just about everywhere in C++1x. (Although Comeau 4.3.9 alpha chokes on fnieto's example.)

sbi
  • 219,715
  • 46
  • 258
  • 445
  • @sbi: even though it won't be out this year, for the sake of everybody's sanity, it's probably best to still call is C++ 0x. As you should expect with '0x' as the prefix, the digit will be in hexadecimal. @frieto: you were right. Draft cited above... – Jerry Coffin Oct 20 '09 at 20:40
  • @Jerry: Please read my comment at http://stackoverflow.com/questions/1536753/1536779#1536779. – sbi Oct 20 '09 at 20:52