Could someone point me to the (official) definition of object in C++? In the current specification, the word "object" is used a few thousand of times, but I can't seem to find a section or reference that explains what an object is.

The background to this somehow basic question is a discussion I recently had with another user, who was surprised to my question of whether a pointer to a variable of a scoped enum type could be considered an object pointer. According to what he says, in C++ each variable is an object, hence also the variable i in int i = 42;. Anyway, I could find other sources stating that an object in C++ is an instance of a class (and this is surely what I was taught at school many years ago), which contradicts in my understanding the assumption above that any variable is an object. Or is there an explanation to this apparent contradiction?

有帮助吗?

解决方案

References aren't objects. Instances of pretty much any other type are.

Here's the definition, found in section 1.8:

The constructs in a C ++ program create, destroy, refer to, access, and manipulate objects. An object is a region of storage. [ Note: A function is not an object, regardless of whether or not it occupies storage in the way that objects do. — end note ] An object is created by a definition (3.1), by a new-expression (5.3.4) or by the implementation (12.2) when needed. The properties of an object are determined when the object is created. An object can have a name (Clause 3). An object has a storage duration (3.7) which influences its lifetime (3.8). An object has a type (3.9). The term object type refers to the type with which the object is created. Some objects are polymorphic (10.3); the implementation generates information associated with each such object that makes it possible to determine that object's type during program execution. For other objects, the interpretation of the values found therein is determined by the type of the expressions (Clause 5) used to access them.

More useful is the definition of object type in 3.9p8:

An object type is a (possibly cv-qualified) type that is not a function type, not a reference type, and not a void type.

Functions have function type but they aren't instances, and there never are instances of void.

To deal with your particular debate, you need the definition of object pointer, from 3.9.2p3:

The type of a pointer to void or a pointer to an object type is called an object pointer type.

As it turns out, the definition of object never mattered, only the definition of object type. A pointer to a scoped enum is certainly an object pointer (and it is itself also an object).

You'll find that the Standard uses the phrase class object when it means to restrict to instances of class, struct, or union type.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top