Thinking in C plus plus (P13)

Tham khảo tài liệu 'thinking in c plus plus (p13)', công nghệ thông tin, kỹ thuật lập trình phục vụ nhu cầu học tập, nghiên cứu và làm việc hiệu quả | initialization before the object is used thus reintroducing a major source of bugs. It also turns out that many programmers seem to find C s dynamic memory functions too confusing and complicated it s not uncommon to find C programmers who use virtual memory machines allocating huge arrays of variables in the static storage area to avoid thinking about dynamic memory allocation. Because C is attempting to make library use safe and effortless for the casual programmer C s approach to dynamic memory is unacceptable. operator new The solution in C is to combine all the actions necessary to create an object into a single operator called new. When you create an object with new using a new-expression it allocates enough storage on the heap to hold the object and calls the constructor for that storage. Thus if you say MyType fp new MyType 1 2 at runtime the equivalent of malloc sizeof MyType s called often it is literally a call to malloc and the constructor for MyType is called with the resulting address as the this pointer using 1 2 as the argument list. By the time the pointer is assigned to fp it s a live initialized object - you can t even get your hands on it before then. It s also automatically the proper MyType type so no cast is necessary. The default new checks to make sure the memory allocation was successful before passing the address to the constructor so you don t have to explicitly determine if the call was successful. Later in the chapter you ll find out what happens if there s no memory left. You can create a new-expression using any constructor available for the class. If the constructor has no arguments you write the new-expression without the constructor argument list 580 Thinking in C www. BruceEckel .com MyType fp new MyType Notice how simple the process of creating objects on the heap becomes - a single expression with all the sizing conversions and safety checks built in. It s as easy to create an object on the heap as it is on the stack. operator

Không thể tạo bản xem trước, hãy bấm tải xuống
TÀI LIỆU MỚI ĐĂNG
Đã phát hiện trình chặn quảng cáo AdBlock
Trang web này phụ thuộc vào doanh thu từ số lần hiển thị quảng cáo để tồn tại. Vui lòng tắt trình chặn quảng cáo của bạn hoặc tạm dừng tính năng chặn quảng cáo cho trang web này.