C++英文面試常見問題

Difference between new/delete and malloc/free

New/delete is C++, malloc/free comes from good old C.

In C++, new calls an objects constructor and delete calls the destructor.

Malloc and free, coming from the dark ages before OO, only allocate and free the memory, without executing any code of the object.

When you new an object, space for the object is not only allocated but the object’s constructor is called.
And similarly when you delete an object, the object’s destructor is called before the memory is released. If you use malloc and free, the destructor and constructor do not get called respectively and obviously, this simply won’t do in C++ except in certain very rare situations where you have classes without any specific destructor/constructors. new is a operator and malloc is a function.

Friend function

A friend function of a class is defined outside that class’s scope but it has the right to access all private and protected members of the class.

Even though the prototypes for friend functions appear in the class definition, friends are not member functions.

A friend can be a function, function template, or member function, or a class or class template, in which case the entire class and all of its members are friends.

Virtual function and pure virtual function

A virtual function or virtual method is a function or method whose behavior can be overridden within an inheriting class by a function with the same signature.

A pure virtual function or pure virtual method is a virtual function that is required to be implemented by a derived class that is not abstract”.

“Virtual” means that the method may be overridden in subclasses, but has an directly-callable implementation in the base class.

“Pure virtual” means it is a virtual method with no directly-callable implementation. Such a method must be overridden at least once in the inheritance hierarchy – if a class has any unimplemented virtual methods, objects of that class cannot be constructed and compilation will fail.

Defining in a base class, a virtual function, with another version in a derived class, signals to the compiler that we don’t want static linkage for this function.
What we do want is the selection of the function to be called at any given point in the program to be based on the kind of object for which it is called. This sort of operation is referred to as dynamic linkage, or late binding.

stack and heap

Stack:It’s a special region of computer’s memory that stores temporary variables created by each function (including the main() function). The stack is a “LIFO” (last in, first out) data structure, that is managed and optimized by the CPU.

Heap: The heap is a region of computer’s memory that is not managed automatically for you, and is not as tightly managed by the CPU. It is a more free-floating region of memory (and is larger). To allocate memory on the heap, you must use malloc(). Once you have allocated memory on the heap, you are responsible for using free() to de-allocate that memory once you don’t need it any more. If you fail to do this, your program will have a memory leak.

When to use stack/heap?

If you need to allocate a large block of memory (e.g. a large array, or a big struct), and you need to keep that variable around a long time (like a global), then you should allocate it on the heap.

If you are dealing with realtively small variables that only need to persist as long as the function using them is alive, then you should use the stack, it’s easier and faster.

If you need variables like arrays and structs that can change size dynamically (e.g. arrays that can grow or shrink as needed) then you will likely need to allocate them on the heap, and use dynamic memory allocation functions like malloc(), calloc(), realloc() and free() to manage that memory “by hand”.

Difference between call by value and call by reference

In call by value, a copy of actual arguments is passed to respective formal arguments. While, in call by reference, the address of actual arguments is passed to formal arguments, hence any change made to formal arguments will also reflect in actual arguments.

If data is passed by value, the data is copied from the variable used in for example main() to a variable used by the function. So if the data passed (that is stored in the function variable) is modified inside the function, the value is only changed in the variable used inside the function.

If data is passed by reference, a pointer to the data is copied instead of the actual variable as is done in a call by value. Because a pointer is copied, if the value at that pointers address is changed in the function, the value is also changed.

smart pointer

A smart pointer is a class that wraps a ‘raw’ (or ‘bare’) C++ pointer, to manage the lifetime of the object.

It simulates a pointer while providing additional features, such as automatic memory management or bounds checking.
These additional features are intended to reduce bugs caused by the misuse of pointers while retaining efficiency.
Smart pointers typically keep track of the memory they point to. They may also be used to manage other resources, such as network connections and file handles. Smart pointers originated in the C++ programming language.

  • Smart pointers prevent most situations of memory leaks by making the memory deallocation automatic.
  • More generally, they make object destruction automatic: the object controlled by a smart pointer is automatically destroyed (finalized and then deallocated) when the last (or only) owner of the object is destroyed
  • Smart pointers also eliminate dangling pointers by postponing destruction until the object is no longer in use.

Difference between queue and stack

Stack is a LIFO (last in first out) data structure.
Queue is a FIFO (first in first out) data structure.

volatile

The volatile keyword is intended to prevent the (pseudo) compiler from applying any optimizations on the code that assume values of variables cannot change “on their own.”

Array, list and vector

Array is collection of homogeneous elements.
List is collection of heterogeneous elements.

For Array, memory allocated is static and continuous.
For List, memory allocated is dynamic and Random.

Array: User need not have to keep in track of next memory allocation.
List: User has to keep in track of next location where memory is allocated.

Array uses direct access of stored members, list uses sequencial access for members.

Vector. It provides an equally rich interface as list and removes the pain of managing memory that arrays require.
They allocate memory from the free space when increasing in size.
They can increase/decrease in size run-time.
The most compelling reason to use a vector is that it frees you from explicit memory management, and it does not leak memory.

Memory leak

Use after free (dangling pointer dereference)
Heap buffer overflow
Stack buffer overflow
Global buffer overflow
Use after return
……

New features in C++

auto
nullptr
Range-based for loops
Override and final
Strongly-typed enums
Smart pointers
Lambdas
non-member begin() and end()
static_assert and type traits
Move semantics
……

發佈了71 篇原創文章 · 獲贊 30 · 訪問量 38萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章