Flovdis
Flovdis

Reputation: 3095

Can the C++ struct aggregate initialisation be used to create temporary instance?

To quickly initialise small structs I often use the aggregate initialisation to keep the code small and simple:

struct Foo {
    int a;
    int b;
    int c;
};
Foo temp = {1, 2, 3};

I would assume this should also work to create a temporary instance which can be passed as function argument:

void myFunc(Foo foo) {
    // ...
}

Is this possible? How is the exact syntax to use this feature?

myFunc({1, 2, 3}); // ???
myFunc(Foo {1, 2, 3}); // ???

Upvotes: 5

Views: 307

Answers (3)

songyuanyao
songyuanyao

Reputation: 172924

The 1st case is copy-list-initialization and pretty fine for your example.

function( { arg1, arg2, ... } ) ; (7)

7) in a function call expression, with braced-init-list used as an argument and list-initialization initializes the function parameter

So for myFunc({1, 2, 3});, myFunc expects a Foo; then the braced-init-list {1, 2, 3} will be used to copy-list-initialize a temporary Foo and being passed to myFunc as the argument.

For myFunc(Foo {1, 2, 3});, a temporary Foo will be direct-list-initialized explicitly, then is passed to myFunc as the argument.

There are some subtle differences between direct-list-initialization and copy-list-initialization, e.g. explicit converting constructor is not considered for copy-list-initialization:

struct Foo {
    // explicit converting constructor
    explicit Foo(int, int, int) {}
    int a;
    int b;
    int c;
};

void myFunc(Foo foo) {
    // ...
}

myFunc({1, 2, 3});      // fail, can't convert from braced-init-list to Foo
myFunc(Foo {1, 2, 3});  // fine

Upvotes: 4

Nir Friedman
Nir Friedman

Reputation: 17704

This small program compiled for me:

#include <iostream>

struct Foo {
    int a;
    int b;
    int c;
};

void bar(const Foo&) {}


int main() {
    bar({1,2,3});
    bar(Foo{1,2,3});
}

The first call is implicit, the second is explicit; both work. If you have a template function or something where implicit conversion does not occur easily then you should use the second form.

Live example: http://coliru.stacked-crooked.com/a/13c9fb9e277be697

Upvotes: 1

Dariusz R.
Dariusz R.

Reputation: 96

Yes, you can use myFunc({1, 2, 3});.

Upvotes: 0

Related Questions