C++基础面试题, C++
C++基础面试题, C++
QA
Step 1
Q:: Explain the concept of RAII (Resource Acquisition Is Initialization) in C++?
A:: RAII is a programming idiom used in C++ where resources such as memory, file handles, or network sockets are acquired and released automatically through object lifetime management. When an object is created, it acquires a resource, and when it goes out of scope, its destructor automatically releases the resource. This helps prevent resource leaks by tying resource management to the object's lifetime.
Step 2
Q:: What are smart pointers in C++? Describe the differences between std::unique_ptr, std::shared_ptr, and std::weak_ptr.
A:: Smart pointers are template classes in C++ that manage the lifetime of dynamically allocated objects. std::unique_ptr is a smart pointer that owns and manages another object exclusively, meaning no other smart pointer can share ownership. std::shared_ptr allows multiple smart pointers to share ownership of an object, and it uses reference counting to track the number of owners. std::weak_ptr, on the other hand, is a smart pointer that holds a non-owning reference to an object managed by std::shared_ptr, thus avoiding circular references.
Step 3
Q:: What is the difference between deep copy and shallow copy in C++?
A:: A shallow copy is a bit-wise copy of an object, meaning it copies the values of all fields as they are. However, if the object contains pointers to dynamically allocated memory, only the pointer values are copied, not the actual data they point to, leading to shared resources between the original and copied objects. A deep copy, on the other hand, involves creating copies of the dynamically allocated memory as well, ensuring that the copied object has its own separate copy of the data.
Step 4
Q:: How does C++ implement polymorphism? Explain the role of virtual functions.
A:: C++ implements polymorphism primarily through virtual functions and inheritance. When a base class declares a function as virtual, derived classes can override this function with their own implementations. The virtual table (vtable) and virtual pointer (vptr) mechanism allows the program to determine at runtime which function to call based on the actual type of the object, enabling runtime polymorphism.
Step 5
Q:: What are move semantics in C++11? How do they differ from copy semantics?
A:: Move semantics in C++11 allow the resources of an object to be 'moved' rather than copied, which can improve performance by avoiding unnecessary deep copies. This is particularly useful when dealing with objects that manage resources like dynamic memory or file handles. Move semantics are implemented using rvalue references (&&) and the std::move function, which allows the transfer of resources from one object to another without copying. This contrasts with copy semantics, where each object would independently manage its own copy of resources.