Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize pointer to structure - compiler warning

#include <iostream>
using namespace std;

struct test
{
   int factorX;
   double coefficient;
};

int main()
{
   test firstTest = {1, 7.5}; //that's ok

   test *secondTest = new test;
   *secondTest = {8, 55.2}; // issue a compiler warning

}

I don't understand why the compiler issues the following warning:

test2.cpp:13:33: warning: extended initializer lists only available with -std=c++11 or -std=gnu++11 [enabled by default]
test2.cpp:13:33: warning: extended initializer lists only available with -std=c++11 or -std=gnu++11 [enabled by default]

I know that in C++11 I can omit the assignment operator but that's not the case. I am using g++ 4.7.2.

like image 270
Toshko Avatar asked Jul 13 '26 19:07

Toshko


1 Answers

Your test structure is an aggregate. While initialization of an aggregate with the braces syntax is supported in C++98, assignment is not.

Here, what is really going on is that the compiler invokes the implicitly generated move-assignment operator, which takes a test&& as its input. In order to make this call legal, the compiler will have to convert {8, 55.2} into an instance of test by constructing a temporary from it, then move-assign *secondTest from this temporary.

This behavior is supported only in C++11, which is why the compiler is telling you that you have to compile with the -std=c++11 option.

like image 137
Andy Prowl Avatar answered Jul 16 '26 07:07

Andy Prowl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!