初始化指向结构的指针 - 编译器警告

Tos*_*hko 3 c++ struct warnings g++ c++11

#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

}
Run Code Online (Sandbox Code Playgroud)

我不明白为什么编译器发出以下警告:

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]
Run Code Online (Sandbox Code Playgroud)

我知道在C++ 11中我可以省略赋值运算符,但事实并非如此.我正在使用g ++ 4.7.2.

And*_*owl 5

您的test结构是一个聚合.虽然在C++ 98中支持使用大括号语法初始化聚合,但分配不是.

这里,真正发生的是编译器调用隐式生成的移动赋值运算符,该运算符将a test&&作为其输入.为了使此调用合法,编译器必须通过从中构造临时转换{8, 55.2}为实例test,然后*secondTest从此临时移动分配.

仅在C++ 11中支持此行为,这就是编译器告诉您必须使用该-std=c++11选项进行编译的原因.