0

Are there benefits to instantiating structs using aggregate initialization as opposed to having an init function to return an instance? This is what I'm talking about:

sturct Data
{
    float x, y;
    std::string dataString;
};

Data init_data(float _x, float _y, std::string _dataString)
{
    Data data;
    data.x = _x;
    data.y = _y;
    data.dataString = _dataString;
    return data;
}

int main()
{
    Data d1 = init_data(1.0, 2.0, "testData"); // or
    Data d2 { 1.0, 2.0, "testData");
}
Neosapien
  • 157
  • 1
  • 13
  • 2
    You seem to be mixing two different things here: 1. Whether or not you use a function returning an object instead of initializing it directly. 2. Whether or not you use aggregate initialization instead of setting fields individually. These two seem orthogonal to me. You could use aggregate initialization in `init_data` as well or set fields individually in `main`. Which of the two are you interested in? – user17732522 Feb 10 '22 at 01:22
  • @user17732522 It's actually more of a choice based on correctness, if there is such a thing. They both seem to be performing equally well, even with large complex structs. I think the compiler helps optimize this to some extent. Do you know which one of these are most used in data-oriented design? I couldn't find specific answers for this scenario. – Neosapien Feb 10 '22 at 08:49

1 Answers1

1

In the sense of performance, probably yes. d2 directly generates the Data instance with specified data values, while d1 is generating the a Data{0,0,empty string} first inside the function, and then modifies the values that you wanted, then return that Data by value, making another copy of Data. although the optimization the compiler offers may reduce the overhead, but it is not guaranteed.

K.R.Park
  • 1,015
  • 1
  • 4
  • 18