Is there a way to initialise a new struct variable that does not involve writing a constructor?

  • A+

I think that I vaguely recall that one of the newer c++ standards (maybe its c++11, or maybe 14?...17??) allows you to initialise a struct, whereby you can define a struct and then initialise it without having to write a constructor.


struct test {     int a;     int b;     std::string str; };  int main() {     std::map<int, test> test_map;     test_map[0] = test(1, 2, "test1"); // This is the line in question     // Or it might be more like: test_map[0] = test{1, 2, "test1"};     return 0; } 

I can't recall the name of this special initialisation (or if it even exists)!. So my questions are:

  • Is there some new mechanism to achieve this without writing a constructor in the struct "test"?
  • If so, what is it called (so I can read more about it).

If this "feature" does not exist then please put me out of my misery!, it could be that my imagination has made this up...

The "initialize without a constructor" is called aggregate initialization, it has always been a part of C++ since day 1. Unfortunately, some might say.

In C++98 you could write:

std::map<int, test> test_map; test temp = { 1, 2, "test1" }; test_map[0] = temp; 

C++11 added that you can use aggregate initialization in prvalues, so you do not need to declare the intermediate variable (and there are no extra copies):

std::map<int, test> test_map; test_map[0] = { 1, 2, "test1" };  std::map<int, test> m2 = { {0, {1, 2, "test2"}} };    // and this 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: