C++ inline functions

For code segments that are often used, they will be encapsulated into functions for convenience. However, stack frames are created when functions are called, adding extra overhead. To save overhead, macro substitution is used in C language. However macros have some disadvantages:

1) cannot be debugged;

2) Since macros use simple text replacement, in some cases, redefinition errors will occur when the same macro is used twice in the same scope.

#define SWAP(a,b)\
	int tmp = a; \
	a = b; \
	b = tmp;
intmain()
{
	int x = 10;
	int y = 5;
	SWAP(x, y);
	SWAP(x, y);//There will be an error here
	system("pause");
	return 0;
}

In C++ , a function decorated with inline is called an inline function. When compiling, the C++ compiler will expand the place where the inline function is called. There is no function stack overhead, and the inline function improves the efficiency of program operation.

1) The inline function is the practice of changing space for time, which saves the extra overhead of calling the function. So functions with very long code or loops/recursions are not suitable for inlining.
2) Inline is just a suggestion for the compiler. If the defined function body has recursion/loop, etc., the compiler will automatically ignore the inline when optimizing.
3) Inline must be placed with the function definition in order to become an inline function, and only placing the inline before the declaration does not work.
4) In general, inline functions are only used when the content of the function is very simple. If there are too many inline function codes, it will cause problems such as poor readability.
class A
{
public:
	/*inline*/ void fun();//It doesn't work here
	
private:
	int a;
};
inline void A::fun()
{
	cout << "inline void A::fun()" << endl;
}

Member functions defined within a class are defined as inline functions by default. You can use protected members and private members of the class in which they belong.

class A
{
public:
	void fun()
{
// default to inline
}	
private:
	int a;
};

1) Why is inline a good replacement for predefined?

1. The inline function defined by Inline, the code of the function is directly replaced when it is used, there is no calling overhead, and the efficiency is improved.

2. The inline function of a class is also a function, and the compiler will check its parameters when calling to eliminate hidden dangers

3. Member functions defined in a class are defined as inline functions by default. You can use protected members and private members of the class in which they belong.



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325528178&siteId=291194637