据我所知,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或聚合并不重要。
- 相关常见问题解答