c++中类对象作为参数都是值拷贝吗?
天蓬老师
天蓬老师 2017-04-17 13:33:17
0
5
434

c++中string作为参数是值拷贝,其他的对象也都是这样的么?

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(5)
伊谢尔伦

Is string used as a parameter in c++ a value copy?

Yes.

Are other objects also like this?

Not necessarily, it depends on the definition of the copy/move constructor. For example: Value-like class and Pointer-like class.

巴扎黑

Since the questioner knows that observing the assembly window, it is easy to find that the copy constructor of the object is called there, so here is by value

In fact, all objects in C++ are treated as by value. If you need by reference, you need to change the function signature to const string& obj

刘奇

1. If the object is passed into the function as a value parameter, such as func (const string obj), the object will be copied and a temporary object will be generated, which affects performance;
2. If the object is used as a reference or pointer When parameters are passed in, such as func (const string &obj), fun (const string *obj), the object will not be copied or copied, and no temporary object will be generated.

巴扎黑

Because the way you pass parameters is by value, the copy constructor is called, which can be replaced by string &x; this is passing a reference. In addition, c++11 has newly added the ability to use string && x to pass temporary variables

Ty80

The method of passing parameters in C++ is value copy (by value) or reference copy (by reference), depending on how you name the formal parameters.

Example 1: Pass by value.

/* function declaration of transferring argument by value */
void func(string s) {
    // operates on string object s
    // note that here s is a copy of the string object you transferred in so any function-scope change will not affect invoker environment.
}

/* example usage of aforementioned function */
string str;
func(str);
// after func call, str will keep the same

Example 2: Pass by reference.

/* function declaration */
void func(string& s) {
    // operate on string object s
    // local change will be applied to the argument you transferred in
}

/* example usage */
string str;
func(str);
// at this time, str will be changed with the modification func() made to it

Example 3: Pass by constant reference (in actual work, this calling method is the most commonly used, it can effectively reduce the memory and CPU time consumption of string copy) .

/* function declaration */
void func(const string& s) {
    // transfer in a read-only reference of string object s
    // no copy will be made against s, neither any change allowed upon it
}

/* example usage */
string str;
func(str);
// str is not supposed to be changed after func() invoke.
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template