Skip to content

Cpp

Main

https://zhuanlan.zhihu.com/p/75347892

  • delete 会调用对象的析构函数,和 new 对应 free 只会释放内存,new 调用构造函数。
  • OOP: 封装,继承和多态。
  • 定义一个对象时先调用基类的构造函数、然后调用派生类的构造函数;析构的时候恰好相反:先调用派生类的析构函数、然后调用基类的析构函数。
  • 虚函数和纯虚函数的区别:定义一个函数为虚函数,不代表函数为不被实现的函数。定义他为虚函数是为了允许用基类的指针来调用子类的这个函数。定义一个函数为纯虚函数,才代表函数没有被实现。定义纯虚函数是为了实现一个接口,起到一个规范的作用,规范继承这个类的程序员必须实现这个函数。
  • overload vs override?
  • C++是不是类型安全的?答案:不是。两个不同类型的指针之间可以强制转换(用 reinterpret cast)。C#是类型安全的。
  • main 函数执行以前,还会执行什么代码?答案:全局对象的构造函数会在 main 函数之前执行。
  • protected: inherited class can access
  • volatile keyword: avoid compiler optimization on the variable reference --> if shared with some other process/language runtime?
  • https://www.geeksforgeeks.org/storage-classes-in-c/
    • Static variables have a property of preserving their value even after they are out of their scope!
      • local static vs global static
    • The main purpose of using extern variables is that they can be accessed between two different files which are part of a large program
    • mutable is a new storage class in C++: The mutable storage class specifier is used only on a class data member to make it modifiable even though the member is part of an object declared as const.
  • Shallow copy vs deep copy: shallow copy is like memcpy, while deep copy uses the copy constructor and/or overloaded assignment operator
  • A class with at least one pure virtual function is called as abstract class. We cannot instantiate an abstract class.
  • wchar_t: undefined, depends on system, used to encoding larger charset
  • ->: is arrow sign
  • boolean 1 byte = char 1 byte
  • When a class member is defined outside the class, which operator can be used to associate the function definition to a particular class?
    • Scope resolution operator :: (double colon)
  • C++ namespace best practices
    • https://google.github.io/styleguide/cppguide.html#Namespaces
    • Namespaces subdivide the global scope into distinct, named scopes, and so are useful for preventing name collisions in the global scope.
    • Namespaces provide a method for preventing name conflicts in large programs while allowing most code to use reasonably short names.
    • Very much like a module system... (include + namespace)
  • Every class does have a constructor provided by the compiler if the programmer doesn’t provides one and known as default constructor
  • Why copy constructor?
    • https://stackoverflow.com/questions/5368258/the-copy-constructor-and-assignment-operator
    • The copy constructor is used to initialize a new instance from an old instance. It is not necessarily called when passing variables by value into functions or as return values out of functions. (RVO)
      • What is RVO? Difference between Return Value Optimization (RVO), Named RVO (NRVO) and Copy-Elision?
      • RVO: avoid creating temporary objects for return values, even if they have side effects
      • NRVO: Named RVO is when an object with a name is returned but is nevertheless not copied. A simple example is:
      • What is move-semantics?
        • Transfer ownership statically to avoid emitting code that copies things over unnecessarily
    • The assignment operator is to deal with an already existing object. The assignment operator is used to change an existing instance to have the same values as the rvalue, which means that the instance has to be destroyed and re-initialized if it has internal dynamic memory.
  • Difference between struct and class: default visibility of the members
  • What is the role of the file opening mode ios::trunk? If the file already exists, its content will be truncated before opening the file.
  • The starting address of the array is called as the base address of the array.
  • A C++ program consists of various tokens and a token is either a keyword, an identifier, a constant, a string literal, or a symbol.
  • g++ –lm -- link math library
  • What is difference between including the header file with-in angular braces <> and double quotes ""
    • If a header file is included with in <> then the compiler searches for the particular header file only with in the built in include path. If a header file is included with in "", then the compiler searches for the particular header file first in the current working directory, if not found then in the built in include path
  • A virtual destructor ensures that the objects resources are released in the reverse order of the object being constructed w.r.t inherited object.
  • C++ supports exceptions while C doesn't.
  • References vs pointers
    • References cannot be rebound.
  • vtable is a table of function pointers per class. vptr is a pointer to vtable per object.
    • Compiler emits code to maintain them.
      • Inside constructor, sets vptr
      • Inside polymorphic function call, compiler inserts code that looks up vptr of the object, and accesses the vtable, then know where the function to call is.
    • Why?
      • there are cases where it is not possible for the compiler to know which routine to execute at compile time.
    • Why happens during down cast?
  • Down cast and up cast in C++?
  • Why it is always a good idea to make destructors of base classes virtual. Since derived classes are often handled via base class references, declaring a non-virtual destructor will be dispatched statically, obfuscating the destructor of the derived class
    • So, for compiler, it interprets things very differently -- if it finds a non-virtual implementation, it will compile all calls to that fixed address. While if declared as a virtual function, it will emit dynamic code that uses the vptr and vtable (which follows some order...)
    • Note that virtual method in base class can also have implementation --> just called later after the derived one.
    • Overriding is implemented as having the same offset for the virtual function and overriding function.
  • 构造函数为什么需要初始化列表?
    • 书写方便
  • How to implement a unique_ptr or shared_ptr? Counters.
  • SFINAE: https://stackoverflow.com/questions/3407633/explain-c-sfinae-to-a-non-c-programmer (keywords: duck typing, template programming)
  • perfect forwarding (C++ 11)
    • emplace and emplace_back: construct the object inside the allocated space of vector. This feature is based on variadic templates and perfect forwarding
    • perfect forwarding problem (similar to kwargs...): Why is this useful? Well, it means that a function template can pass its arguments through to another function whilst retaining the lvalue/rvalue nature of the function arguments by using std::forward. This is called "perfect forwarding", avoids excessive copying, and avoids the template author having to write multiple overloads for lvalue and rvalue references.
  • move constructor: https://stackoverflow.com/questions/3106110/what-is-move-semantics
    • rvalue reference: f(T&& x)
    • To summarize, the copy constructor makes a deep copy, because the source must remain untouched. The move constructor, on the other hand, can just copy the pointer and then set the pointer in the source to null.
  • https://en.wikipedia.org/wiki/Rule_of_three_%28C++_programming%29
  • Best C++11 Features
    • Lambda expressions
    • auto
    • delete function: prevent copy
    • nullptr
    • rvalue references
    • shared_ptr and unique_ptr
    • concurrency
  • Best C++ 14 features
  • main can't return avoid in C++
  • Using smart pointer or vector instead of raw pointer to avoid leakage esp. when there could be exception
  • Examples of UB (Undefined Behaviors)?
    • Dereferencing a null or wild pointer
    • Access uninitialized memory
    • Repeated deleting of memory
    • Division by zero
  • memory barrier https://stackoverflow.com/questions/286629/what-is-a-memory-fence
  • Is stack faster than heap? Why
    • Allocation and deallocate is done in batch
    • Addressing is static
    • Better cacheline performance

C

Low-latency

  • Use config + template: virtual calls are expensive
  • lambda + template: inlined functionality without sacrificing expressibility
  • Use a pool of pre-allocated objects
  • Avoid multi-threading
  • Some times duplicating the data to obtain it in the same cacheline
  • Hybrid of chaining and open-address: saving only metadata in hashtable in order to put more conflicting hash keys in the same cacheline.
  • Excessive inlining will bring code you don't want into the code cacheline.
  • Keep cache hot for the critical full codepath: run a frequent dummy path
    • Inverse of importance: things happens rarely are more important
  • profiling vs. benchmarking
    • profiling can catch surprises
    • microbenchmark are not very realistic either
    • e2e benchmarking reflects the prod better

Multi-threaded Programming

  • How do multi-core system ensure that the cache is in sync?
  • What synchronization primitives do you know, tell difference between them.
    • Semaphore
    • Mutex
    • Signals (inter-process)
    • Conditional variables: A condition variable allows a thread to be signaled when something of interest to that thread occurs.
    • Monitors: (synchronized)
    • Atomic instruction: test-and-set, CAS etc.
    • NOTE that semaphore and mutex etc. are still implemented with hardware instruction that ensure atomicity of decrement/increment -- but they are used to protect a larger segment of code.
  • What is a race condition. https://stackoverflow.com/questions/34510/what-is-a-race-condition
  • What is the best way to terminate a thread?
    • Let the thread terminate itself?
    • https://stackoverflow.com/questions/12207684/how-do-i-terminate-a-thread-in-c11
    • Some clean up work? Leaky resource?
    • In fact there is no any language or any operating system which provide you facilities for asynchronous abruptly thread termination without warning to not use them.
    • cooperative or synchronous thread termination
      • while (running) { ... do work ... }
    • As a result thread termination at the arbitrary moment means killing it at arbitrary point of its execution path and can easily lead to the process-wide data corruption, memory and handles leakage, threads leakage and spinlocks and other intra-process synchronization primitives leaved in the closed state preventing other threads in doing progress.
  • Race conditions can be solved by async I/O as well.
  • What are ephemeral ports