I have a function like this
void func(SomeObject obj)
{
...
}
int main()
{
SomeObject obj = GetSomeObject();
func(std::move(obj));
return 0
}
My question is, since func()
takes parameter by value, will the copy constructor be called or the move constructor, even after std::move()
? Or should I need to change function signature like below?
void func(SomeObject&& obj)
{
...
}
Also what is preferred way ? func(SomeObject&& obj)
or func(SomeObject obj)
? In what situation I should prefer one over the other with std::move()?
If SomeObject
has a move constructor defined, then calling func(std::move(obj))
will construct the obj
parameter using the move constructor. If there is no move constructor defined, then the obj
parameter will be constructed using the copy constructor instead.
If there is no copy or move constructor defined, the compile will fail with an error.
If you change the obj
parameter to be an rvalue reference, no construction will be done at all, the result of std::move(obj)
will be passed as-is, like any other reference parameter.
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.