Method parameter copied (not moved)

Flaviu_ 1,031 Reputation points
2023-11-08T11:42:04+00:00

I have the following code:

// header
	void Method1(const bool& b, std::vector<int>&& v);
	bool Method2();
bool CMyClass::Method1()
{
	std::vector<int> v{ 1, 2, 3 };
	TRACE("%d\n", v.size());
	Method2(true, std::move(v));
	TRACE("%d\n", v.size());
	return true;
}

void CMyClass::Method2(const bool& b, std::vector<int>&& v)
{
	TRACE("%d\n", v.size());
}

Outcome:

3

3

3

Why v is copied, but not moved?

Developer technologies | C++
{count} votes

Accepted answer
  1. Minxin Yu 13,506 Reputation points Microsoft External Staff
    2023-11-09T02:50:48.3733333+00:00

    std::move does not mean move action. It casts. signals that it can be moved

    move

    Unconditionally casts its argument to an rvalue reference, and thereby signals that it can be moved if its type is move-enabled.

    You are just binding an rvalue reference to the vector you pass; not moving.

    Compare the example:
    Output:
    3

    temp is 3

    v is 0

    0

    #include <iostream>
    #include <vector>
    
    std::vector<int> v{ 1,2,3 };
    void Method2(const bool& b, std::vector<int> temp)
    {
    
    	std::cout << "temp is "<<temp.size()<<std::endl;
    	std::cout <<"v is " <<v.size() << std::endl;
    
    
    }
    
    bool Method1()
    {	
    	std::cout << v.size() << std::endl;
    	Method2(true, std::move(v));
    	std::cout << v.size() << std::endl;
    
    	return true;
    }
    
    
    int main()
    {
    	Method1();
    
    }
    

    Best regards,

    Minxin Yu


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.