简体   繁体   中英

C++ function argument passed by value

I know that when you call a function this way :

foo(MyClass a)

The object a is being passed by value meaning it's being copied.

My question is how is it being copied? say my class don't have a copy constructor, so if it is passed using shallow copy than the object may change inside the function?

Compiler automatically generates the code for the copy constructor and performs member wise copy. The copy constructor which compiler calls does member wise copy which is indeed shallow copy.

It is inadvisable to pass an object by value if a pointer in your class exists. Even if a pointer does not exist, but a dozen other data members exist, they would require a lot of time to get copied.Pass it by reference, and make it const if you dont want its value to be changed.

There are two possibilities.

First: You didn't specify a copy constructor.

In this case the default copy constructor MyClass::MyClass(MyClass const&) will be used. This will attempt to copy construct all of MyClass 's member (recursively, as these may have members themselves). If any of these members is not copy constructible your default copy constructor will therefore fail as well (see next point).

Second: You declared the copy constructor private or actually delete d it (in C++11).

In this case, you will not be able to pass anything to this function, because the compiler will require access to a copy constructor, which you denied it. This will lead to compile time errors.

编译器创建一个默认的复制构造函数。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM