What are the advantages of const string& over const string when passing parameters?

Pass-by-value and pass-by-reference in C++.
C++'s pass-by-value is to copy the value from the calling place to the function. There are two problems. First, the actual parameter needs to be copied to the formal parameter to form a copy of the actual parameter. , there is time and space overhead. If the actual parameter is a structure or class, then the time and space overhead will be very large; second, the modification of the actual parameter copy in the function will not affect the value of the actual parameter at the function call location.
C++'s pass-by-reference , on the one hand, the parameter transfer is to copy the address of the actual parameter to the formal parameter, so that the formal parameter and the actual parameter correspond to the same memory address, then the modification of the formal parameter It will naturally be reflected on the actual parameters; on the other hand, pointers or references in C++ only occupy 4 bytes, so the space-time overhead is acceptable.

Well, let's now look at the comparison of const string & parameter and const string parameter

In the parameter declaration, const, const string parameter indicates that you will not modify the copied copy (that is, the formal parameter). const string & parameter indicates that you will not modify the actual parameters of the calling function

on the other hand:

Because C++ stipulates that a reference cannot be null, you can use it directly when a function is passed in as a reference, and you also need to determine whether the pointer is null
if pass a value directly, you need to create a new temporary object for the object - this step The copy constructor needs to be called. If the object itself is relatively large, it will cause a serious waste of resources. And pass-by-reference can avoid this - if we need read-only access to an object, using constant references can effectively avoid wasting resources

Reference URL:
What are the advantages of const string& over const string when passing parameters?

Guess you like

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