我可以使用“brace init list”初始化包含“std::string”字段的结构吗



据我所知,std::string是非POD类型
当我定义一个包含std::string字段的结构时
我仍然可以使用brace-init-list来初始化结构吗
下面的代码有效。编译器不会给我任何警告。我是不是错过了什么?

#include <stdio.h>
#include <string>
int main()
{
    struct Book
    {
        int id;
        std::string title;
    };
    Book book = {42, "hello, world"};
    printf("%d:%sn", book.id, book.title.c_str());
}

$ g++ --version
g++ (GCC) 4.1.2 20070925 (Red Hat 4.1.2-33)
$ g++ -Wall -std=c++98 main.cpp -lstdc++
$ ./a.out
42:hello, world

Book类型是一个聚合,因此使用聚合初始化语法是非常好的。成员本身是否是POD或聚合并不重要。

  • 相关常见问题解答

最新更新