C++ review

Preparation for the interview regarding the c++ questions. Just go through it to make sure that you can answer everything correctly.

Memory Management

malloc/free

new delete

shallow copy vs deep copy

constructor vs deconstructor

different types of constructor (default, parameterized, copy constructor)

why destructor matters

why need vitual destructor (pure virtual destructor)(undefined behaviours, regarding the deleting resource through the pointer to the base class)

reference vs pointers:

(can’t changed, not NULL, need to be initialised)

lvalue vs rvalue, rvalue reference with rvalue reference

(advanced topic, perfecting forward)

nullptr vs NULL (one type is pointer, another type is int and value is zero)

smart pointer in c++ (unique_ptr, shared_ptr, weak_ptr)

why need std::ref

storage class in C/C++:

auto, static, register(keyword:register), external (keyword:extern)

const vs static

const return value vs const function vs const members

explain details about the automatic object (auto in c++ is different with original one)

iterator and smart pointers (for shared pointer what is overhead for it???)

OOP (object oriented programming)

key concepts about the OOP (abstraction, encapsulation, inheritance, polymorphism)

template defination

difference between class and struct

class access specifiers (public, private, protected)

what is diamond problem and how to solve it

Rule of Five(Write a copy constructor, move constructor, copy assignment operator, and move assignment operator)

when to use virtual function

pure virtual function and the abstract class

types of the inheritences(single, multiple, multilevel, hierachical, hybrid)

virtual table and virtual pointer

friend class and friend function

size of the empty class with the normal function and the virtual function

namespace and it’s using context

RAII

Template

defination

CRPT

Multi-thread

conditional variable

c++11 new features

bind

rvalue reference

std::move

lamda expression (anonymous function)

std::function

async

future and promise

packaged_task

Others

exceptions (different between throw and throw object)

#ifdef and #endif

translation unit

key word: volatile

details about the iterator in c++

useful resources

Answers

Memory management

malloc/free is used to allocate and free the continuous memory space

new/delete is operator in cpp, they will call the constructor and destructor of associated object. malloc is c library, malloc return void pointer, new return the pointer to object (new is type safe)

shallow copy vs deep copy, shallow copy only copy the pointer and deep copy will copy contents from one project to another project.

constructor vs deconstructor, constructor will be called when then object is created and destructor will be called when the object is destroied.

Different types of constructor: Default constructor will be called by the compiler itsself. Parameterized can be used when there are parameters are needed in creating the object. Copy constructor is used when copy from one object to another object.

Why destructor matters, if there is no destructor or customized destructor, the resource will not be released properly. It will also clean up the other resources used by the object.

why need vitual destructor (pure virtual destructor): if there is no destructor in the child class, there might exist undefined behaviours, if deleting resource from the base pointer, there might be some issues when destroying the object.

reference vs pointers: pointer store the address of the memory space. reference can be a alias of the variable (it have same address with the original value). The reference can not be reassigned. It does not have null value. Check this blog for more details.

lvalue vs rvalue, rvalue reference with rvalue reference. Refer to this in detail.

(advanced topic) perfecting forward related to the lvalue and rvalue: (1) understand the diff between lvalue and rvalue (2) understand the forward keyword (3) using the template parameter. Assuming there is a template type, and in the function parameter, we define it as

template <class T>
void wrapper(T&& arg){ foo(std::forward<T>(args))}

foo(T&& n)//rvalue is used in parameter
foo(T& n) //lvalue is used in parameter

this forwarding could help us to detect if the T is a rvalue or a rvalue, if it is a lvalue, the type is changed to lvalue, otherwise, it is rvalue. The coresponding function for foo will be used. Look at example here in detail.

nullptr vs NULL (one type is pointer, another type is int and value is zero)

smart pointer in c++ (unique_ptr, shared_ptr, weak_ptr) refer to this the owner ship is the key idea. weak pointer is to access the pointer but not own it.

why need std::ref (std::ref is act like & except std::ref is copyable and reassignable) there is an example here, the parameter in function is also a reference.

storage class in C/C++: storage class define the scople and lifetiem of variable or functions. Typical include: auto, static, register(keyword:register), external (keyword:extern), auto can be only used within function, like local vairable, register means that the variable need to be stored in register not RAM. static means memory initilized once before the program start. Keep this variable during the lifetime of the program. extern is used to declare a global function or variable defined in other files.

Difference between const and static: check this in detail. Once static is defined, the memory staies there. It is defined onece.

explain details about the automatic object (auto in c++ is different with autonomic object one) if objects is constructed by compiler and destroyed automatically it is autonomic object. It is typically declared on stack and destroyed when out of the scope.

const function vs const members vs const return value:

const variabe is easy to understand, we define a parameter as const in a functionm it usually means that this variable is only readable and we can not change its value in function, otherwise, there is compiling error.

const function (put the const at the end of the function) means that this function will not change any members of associated class. This is a good reference. Even if the const function calls a non-const function, it is still does not compile. (A const function can only call another const function)

Be careful about returning a const value. The temporarny object can not be a const value. (It is meaningless to use const to declare the temporaray value. It might ok return an left variance which is a const)

for shared pointer what is overhead for it: The ovehread for storing the counuter. Refer to this There is overhead for maintaing metadata (the reference counter), when constructing or deleting, there is also autonomic increasing/decreasing opreations each time when create/desrtoy object.

OOP related questions

key concepts about the OOP (abstraction, encapsulation, inheritance, polymorphism, maybe using an example to show these, such as support multiple backends.)

difference between class and struct, property of the element: for struct, all members are public, class have different declaration for these properties.

class access specifiers (public, private, protected, friend): public field, other classes out of current class can access. private, other class can not access class member, we need to use get or set function. protected, in inherited class, it is ok to access associated field, but in other class, we can not access associated field. The friend keyword enable any class to access private and protected members of other class and function.

what is diamond problem, issue of it, and how to solve it, when you inherit from two classes, there might be two branches and two inherit path, two parent classes inherit from the same grandparent class, and both parent classes are inherited by a single child class. Issue of it: The constructor of grand parent will be called twice. Solution is to use virtual keyword in order to aoivd two copy of grand parent class. Virtual inherit is used in this scenario, it tries to guarantee only one parent is in multi inherit scenarios.

Rule of Five(Write a copy constructor, move constructor, copy assignment operator, and move assignment operator): refer to this

when to use virtual function, using virtual function when there is runtime polymorphism, it can guarantee that the correct function is called. When we call this virtual function, it will find the correct function defined in children class.

pure virtual function and the abstract class: we need to override the pure virtual function, there is no defination of in the base class for the pure virtual function. abstract class does not provide all implementation of associated functions.

types of the inheritences (single, multiple, multilevel, hierachical, hybrid)

virtual table and virtual pointer: virtual table is a lookup table of functions used to resolve function calls in a dynamic/late binding manner.

friend class and friend function

size of the empty class with the normal function and the virtual function

namespace and it’s using context

RAII: Scope-Bound Resource Management, when the resource is out of the scope, the object will be destroied. Refer to this question.

template

Template defination and explicit initilization: just use template key word and assocaited type or variable values. Use explicit initilziation to decrease the compiling time.

CRPT (curiously recurring template pattern): A kind of wrapper class, it has a template parameter, which can be the type of children classes. The children class inherit from this wrapper class. In this example, the root class is Shape, then the ShapeCRPT inherit from base class. The concrete Rectangle and Circle inheric from ShapeCRPT and the Rectange and Circle using them self as the template parameter when inherit from the ShapeCRPT, when use the Base class pointer to point the children class, we can still get the right function call.

trailing return type: This blog provides a good explanation. When the return type depednes on the template araument, it is hard to declare the function, in this case we use the trailling return type:

template<typename A, typename B>
auto multiply(A a, B b) -> decltype(a*b) { return a*b; }

it can be used together with lambda expression.

Multi-thread

conditional variable

The condition_variable class is a synchronization primitive used with a std::mutex to block one or more threads until another thread both modifies a shared variable (the condition) and notifies the condition_variable.

When nothing change, it will wait here, once other thread modifies the condition variable, the thead that wait on the condition variable will be notified. The condition variable should be used with mutex together.

After notifying, we can actually check the indicator, if it is not updated, other threads can continue wait. (refer to this blog to get more details)

typical functions associated with conditional variable are wait, notify_one, notify_all

C++11 new features

bind: bind a function with a specific parameter value. If there are two parameters for the function, we can bind the function with one value, then if we want to call the return results of the bind, we just need to use one parameter.

rvalue reference. explained in previous sections

std::move. explained in previous sections

lamda expression (anonymous function) this is a good explanation. (a trailing return type is a syntax feature that specifies the return type of a function after the parameter list)

std::function general wrapper about sth that can be called.

async: The function template std::async runs the function f asynchronously (potentially in a separate thread which might be a part of a thread pool) and returns a std::future that will eventually hold the result of that function call. (the future is like the handler/request of MPI_Irecv)

future and promise: the concepts related to multi-thread programming in cpp. The promise is used to set value in the sender. Which is similar to the producer of the channel in golong. This example show simple idea, after the thread call, we put data through promise and get data through future.

packaged_task A packaged_task wraps a callable element and allows its result to be retrieved asynchronously. It is similar to std::function, but transferring its result automatically to a future object.

Other points

exceptions (different between throw and throw object)

#ifdef and #endif, when define the .h file, we need to add this to make sure the header file is not included multiple times in the .cxx file during the compiling.

translation unit: This is a good explanation. It consists of the contents of a single source file, plus the contents of any header files directly or indirectly included by it, minus those lines that were ignored using conditional preprocessing statements. A single translation unit can be compiled into an object file, library, or executable program.

key word: volatile: volatile prevents the compiler from optimizing code/or the variable with volatile.

details about the iterator in c++ (some implementation ideas, build pointer, left and right reference to the customized class, and also the operation such as ++ – get set etc.)

the new feature you want to add to cpp: borrow idea from golong, define the source remover, and remove resource at the end of the function. sth like defer. It can be defined after the rellocation of the resource, which is easy for programming.

推荐文章