B. Stroustrup - The C++ Programming Language (794319), страница 50
Текст из файла (страница 50)
However, until the completion ofthe declaration of a struct, that struct is an incomplete type. For example:struct S; // ‘‘S’’ is the name of some typeextern S a;S f();void g(S);S∗ h(S∗);However, many such declarations cannot be used unless the type S is defined:void k(S∗ p){S a;// error: S not defined; size needed to allocatef();g(a);p−>m = 7;// error: S not defined; size needed to return value// error: S not defined; size needed to pass argument// error: S not defined; member name not knownS∗ q = h(p);q−>m = 7;// ok: pointers can be allocated and passed// error: S not defined; member name not known}For reasons that reach into the prehistory of C, it is possible to declare a struct and a non-struct withthe same name in the same scope. For example:struct stat { /* ...
*/ };int stat(char∗ name, struct stat∗ buf);In that case, the plain name (stat) is the name of the non-struct, and the struct must be referred towith the prefix struct. Similarly, the keywords class, union (§8.3), and enum (§8.4) can be used asprefixes for disambiguation.
However, it is best not to overload names to make such explicit disambiguation necessary.206Structures, Unions, and EnumerationsChapter 88.2.3 Structures and ClassesA struct is simply a class where the members are public by default. So, a struct can have memberfunctions (§2.3.2, Chapter 16). In particular, a struct can have constructors. For example:struct Points {vector<Point> elem;// must contain at least one PointPoints(Point p0) { elem.push_back(p0);}Points(Point p0, Point p1) { elem.push_back(p0); elem.push_back(p1); }// ...};Points x0;Points x1{ {100,200} };Points x1{ {100,200}, {300,400} };// error : no default constructor// one Point// two PointsYou do not need to define a constructor simply to initialize members in order. For example:struct Point {int x, y;};Point p0;Point p1 {};Point p2 {1};Point p3 {1,2};// danger: uninitialized if in local scope (§6.3.5.1)// default construction: {{},{}}; that is {0.0}// the second member is default constructed: {1,{}}; that is {1,0}// {1,2}Constructors are needed if you need to reorder arguments, validate arguments, modify arguments,establish invariants (§2.4.3.2, §13.4), etc.
For example:struct Address {string name;int number;string street;string town;char state[2];char zip[5];// "Jim Dandy"// 61// "South St"// "New Providence"// ’N’ ’J’// 07974Address(const string n, int nu, const string& s, const string& t, const string& st, int z);};Here, I added a constructor to ensure that every member was initialized and to allow me to use astring and an int for the postal code, rather than fiddling with individual characters. For example:Address jd = {"Jim Dandy",61, "South St","New Providence","NJ", 7974};// (07974 would be octal; §6.2.4.1)The Address constructor might be defined like this:Section 8.2.3Structures and Classes207Address::Address(const string& n, int nu, const string& s, const string& t, const string& st, int z)// validate postal code:name{n},number{nu},street{s},town{t}{if (st.size()!=2)error("State abbreviation should be two characters")state = {st[0],st[1]};// store postal code as charactersostringstream ost;// an output string stream; see §38.4.2ost << z;// extract characters from intstring zi {ost.str()};switch (zi.size()) {case 5:zip = {zi[0], zi[1], zi[2], zi[3], zi[4]};break;case 4: // star ts with ’0’zip = {'0', zi[0], zi[1], zi[2], zi[3]};break;default:error("unexpected ZIP code format");}// ...
check that the code makes sense ...}8.2.4 Structures and ArraysNaturally, we can have arrays of structs and structs containing arrays. For example:struct Point {int x,y};Point points[3] {{1,2},{3,4},{5,6}};int x2 = points[2].x;struct Array {Point elem[3];};Array points2 {{1,2},{3,4},{5,6}};int y2 = points2.elem[2].y;Placing a built-in array in a struct allows us to treat that array as an object: we can copy the structcontaining it in initialization (including argument passing and function return) and assignment.
Forexample:208Structures, Unions, and EnumerationsChapter 8Array shift(Array a, Point p){for (int i=0; i!=3; ++i) {a.elem[i].x += p.x;a.elem[i].y += p.y;}return a;}Array ax = shift(points2,{10,20});The notation for Array is a bit primitive: Why i!=3? Why keep repeating .elem[i]? Why just elements of type Point? The standard library provides std::array (§34.2.1) as a more complete and elegant development of the idea of a fixed-size array as a struct:template<typename T, size_t N >struct array { // simplified (see §34.2.1)T elem[N];T∗ begin() noexcept { return elem; }const T∗ begin() const noexcept {return elem; }T∗ end() noexcept { return elem+N; }const T∗ end() const noexcept { return elem+N; }constexpr size_t size() noexcept;T& operator[](size_t n) { return elem[n]; }const T& operator[](size_type n) const { return elem[n]; }T ∗ data() noexcept { return elem; }const T ∗ data() const noexcept { return elem; }// ...};This array is a template to allow arbitrary numbers of elements of arbitrary types.
It also dealsdirectly with the possibility of exceptions (§13.5.1.1) and const objects (§16.2.9.1). Using array,we can now write:struct Point {int x,y};using Array = array<Point,3>; // array of 3 PointsArray points {{1,2},{3,4},{5,6}};int x2 = points[2].x;int y2 = points[2].y;Section 8.2.4Structures and Arrays209Array shift(Array a, Point p){for (int i=0; i!=a.size(); ++i) {a[i].x += p.x;a[i].y += p.y;}return a;}Array ax = shift(points,{10,20});The main advantages of std::array over a built-in array are that it is a proper object type (has assignment, etc.) and does not implicitly convert to a pointer to an individual element:ostream& operator<<(ostream& os, Point p){cout << '{' << p[i].x << ',' << p[i].y << '}';}void print(Point a[],int s) // must specify number of elements{for (int i=0; i!=s; ++i)cout << a[i] << '\n';}template<typename T, int N>void print(array<T,N>& a){for (int i=0; i!=a.size(); ++i)cout << a[i] << '\n';}Point point1[] = {{1,2},{3,4},{5,6}};array<Point,3> point2 = {{1,2},{3,4},{5,6}};void f(){print(point1,4);print(point2);}// 3 elements// 3 elements// 4 is a bad errorThe disadvantage of std::array compared to a built-in array is that we can’t deduce the number ofelements from the length of the initializer:Point point1[] = {{1,2},{3,4},{5,6}};array<Point,3> point2 = {{1,2},{3,4},{5,6}};array<Point> point3 = {{1,2},{3,4},{5,6}};// 3 elements// 3 elements// error : number of elements not given210Structures, Unions, and EnumerationsChapter 88.2.5 Type EquivalenceTwo structs are different types even when they have the same members.
For example:struct S1 { int a; };struct S2 { int a; };S1and S2 are two different types, so:S1 x;S2 y = x; // error : type mismatchA struct is also a different type from a type used as a member. For example:S1 x;int i = x; // error : type mismatchEvery struct must have a unique definition in a program (§15.2.3).8.2.6 Plain Old DataSometimes, we want to treat an object as just ‘‘plain old data’’ (a contiguous sequence of bytes inmemory) and not worry about more advanced semantic notions, such as run-time polymorphism(§3.2.3, §20.3.2), user-defined copy semantics (§3.3, §17.5), etc.
Often, the reason for doing so isto be able to move objects around in the most efficient way the hardware is capable of. For example, copying a 100-element array using 100 calls of a copy constructor is unlikely to be as fast ascalling std::memcpy(), which typically simply uses a block-move machine instruction. Even if theconstructor is inlined, it could be hard for an optimizer to discover this optimization.
Such ‘‘tricks’’are not uncommon, and are important, in implementations of containers, such as vector, and in lowlevel I/O routines. They are unnecessary and should be avoided in higher-level code.So, a POD (‘‘Plain Old Data’’) is an object that can be manipulated as ‘‘just data’’ without worrying about complications of class layouts or user-defined semantics for construction, copy, andmove.
For example:struct S0 { };struct S1 { int a; };struct S2 { int a; S2(int aa) : a(aa) { } };struct S3 { int a; S3(int aa) : a(aa) { } S3() {} };struct S4 { int a; S4(int aa) : a(aa) { } S4() = default; };struct S5 { virtual void f(); /* ... */ };struct S6 : S1 { };struct S7 : S0 { int b; };struct S8 : S1 { int b; };struct S9 : S0, S1 {};// a POD// a POD// not a POD (no default constructor)// a POD (user-defined default constructor)// a POD// not a POD (has a virtual function)// a POD// a POD// not a POD (data in both S1 and S8)// a PODFor us to manipulate an object as ‘‘just data’’ (as a POD), the object must• not have a complicated layout (e.g., with a vptr; (§3.2.3, §20.3.2),• not have nonstandard (user-defined) copy semantics, and• have a trivial default constructor.Obviously, we need to be precise about the definition of POD so that we only use suchSection 8.2.6Plain Old Data211optimizations where they don’t break any language guarantees.