2

As far as I known, std::string is a non-POD type.
When I define a struct which contains std::string field.
Can I still use the brace-init-list to initialize the struct?
The code bellow works. Compiler gives me no warning. Am I missing something?

#include <stdio.h>
#include <string>

int main()
{
    struct Book
    {
        int id;
        std::string title;
    };

    Book book = {42, "hello, world"};
    printf("%d:%s\n", 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
kev
  • 155,172
  • 47
  • 273
  • 272

1 Answers1

4

The Book type is an aggregate, hence using the aggregate initialization syntax is perfectly fine. Whether or not the members themselves are PODs or aggregates does not matter at all.

Community
  • 1
  • 1
fredoverflow
  • 256,549
  • 94
  • 388
  • 662
  • `"Whether or not the members themselves are PODs or aggregates does not matter at all."`. It does matter in C++03. – Nawaz Feb 13 '12 at 08:34
  • 3
    `An aggregate is an array or a class (clause 9) with no user-declared constructors (12.1), no private or protected non-static data members (clause 11), no base classes (clause 10), and no virtual functions (10.3).` Hence, the Book type *is* an aggregate. – fredoverflow Feb 13 '12 at 08:40