C + + Primer Learning notes _107_ special tools and techniques-inherent non-portable features [top]

Source: Internet
Author: User
Tags bitwise operators

Special tools and technologies-inherent non-portable features [on]

Non-portable features that C + + inherits from the C language: bit fields and volatile qualifiers . These features make it easier to communicate directly with the hardware interface.

C + + also adds another non-portable feature (inherited from the C language): link Indication , which makes it possible to link to programs written in other languages.

One.bit field

You can declare a special class data member, called a bit field, to hold a specific number of bits. bit fields are typically used when a program needs to pass binary data to another program or hardware device .

the layout of bit fields in memory is machine-dependent.

The bit field must be an integer data type, either signed or unsigned. Indicates that the member is a bit field by appending a colon followed by the member name and a constant expression that specifies the number of digits:

typedef unsigned int bit;class file{    Bit mode:2;    Bit modified:1;    Bit Prot_owner:3;    Bit Prot_group:3;    Bit prot_world:3;};/ /WIN7X64,GCC compiler cout << sizeof (File) << Endl;


The mode bit field has two bits,modified only one, and each of the other members has three bits. provides storage compression (if possible) by compressing the bit fields defined in the class definition in neighboring order in adjacent bits of the same integer . For example, in the preceding declaration,5 single-digit fields are stored in a unsigned int that is first associated with the bit field mode . Whether bits are compressed into integers and how they are compressed is related to the machine.

[Be careful !]

It is generally preferable to set the bit field to the unsigned type . stored in signed The behavior of bit fields in a type is defined by the implementation .

Using bit fields

Access bit fields in the same way as other data members of the class

void File::write () {    modified = 1;    //...} void File::close () {    if (modified)    {        //...    }}

Bit fields with more than one bit are typically manipulated using the built-in bitwise operators :

enum {READ = 01,write = 02};int Main () {    File myFile;    Myfile.mode |= READ;    if (Myfile.mode & Read)        cout << "Myfile.mode READ is set" << Endl;}

A class that defines a bit-field member typically also defines a set of inline functions to test and set the value of a bit field . as :

inline int file::isread () const{    return mode & READ;} inline int file::iswrite () const{    return mode & WRITE;}

With these functions , It is now possible to declare a bit field as a Private member of the File class .

The address operator (&) cannot be applied to a bit field, so there is no way to have a pointer to a class bit field, or a bit field to be a static member of a class.

Attached: File class Complete Definition class File{public:    inline int isread () const;    inline int iswrite () const;    inline void Setread ();    inline void Setwrite ();p rivate:    enum {READ = 01,write = ();    typedef unsigned int bit;private:    Bit mode:       2;    Bit modified:   1;    Bit Prot_owner:3;    Bit Prot_group:3;    Bit Prot_world:3;}; inline int file::isread () const{    return mode & READ;} inline int file::iswrite () const{    return mode & WRITE;} inline void File::setread () {    mode |= READ;} inline void File::setwrite () {    mode |= WRITE;} int main () {    File myFile;    Myfile.setread ();    if (Myfile.isread ())        cout << "Myfile.mode READ is set" << Endl;

Two. VolatileQualifier

[Be careful !]

the exact meaning of Volatile is machine -related and can only be understood by reading the compiler documentation ; Use volatile program must change when porting to a new machine or compiler .

Programs that deal directly with hardware often have such data members whose values are controlled by processes outside of the program's own direct control. For example, a program can contain variables that are updated by the system clock. You should declare an object as volatilewhen you can change the value of the object in a manner other than the control or detection of the compiler. the keyword volatile is an indication to the compiler that the optimization should not be performed on such an object .

Use the volatile qualifier in the same way as the Const Qualifier. volatile a qualifier is an additional modifier on a type:

    volatile int display_register;    Volatile Task *curr_task;    volatile int ixa[max_size];    volatile screen bitmap_buf;

Display_registeris ainttype ofvolatileobject;Curr_taskis avolatilethe pointer to the object;Ixais an integer.volatilearray in which each element of the array is considered to bevolatileof;Bitmap_bufis aVolatile Screenobject, every member of it is considered to bevolatilethe.

A class can also define a member function as volatilein the same way that a const member function is defined, and avolatile object can only invoke volatile The member function.

Once you have learned the interaction between a const qualifier and a pointer, The same interaction exists between the volatile qualifier and the pointer. You can declare a volatile pointer , A pointer to a volatile object , and point to the volatile object that volatile Pointers :

    volatile int v;    int *volatile VIP;    volatile int *IVP;    volatile int *volatile VIVP;    int *ip = &v;   Error    VIP = &v;   Error    IVP = &v;   OK    VIVP = &v;  Ok

As with const , you can only Assign the address of a volatile object to a pointer to volatile, or point to A pointer to a volatile type is copied to The pointer that points to it. Only when a reference is volatile can we Initialize the reference with a volatile object.

Synthetic copy control is not available forvolatileObject

An important difference between const and volatile is that you cannot initialize or assign values from volatile objects using synthetic copy and assignment operators . Synthetic Copy Control members accept const parameters, which are const references to class types , but cannot be volatile object is passed to a normal reference or Const references.

If the class wants to allow the volatile object to be copied, or if the class wants to allow the volatile operand or the volatile operand to be assigned , it must define its own copy constructor and/or assignment operator version:

Class Foo{public:    Foo (const volatile Foo &);    Foo &operator= (volatile const Foo &);    Foo &operator= (const volatile Foo &) volatile;};

By defining the parameters of a copy control member as a const volatile reference , we can copy or assign values from any of the various types of foo objects: normal foo Object ,const foo object ,volatile foo object , or const volatile Foo object .

[ caution ]

Although you can define a replication control member to handle  volatile   copy  volatile  object is meaningful , answer to this question and use  volatile  .

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.