Home > Back-end >  C universal reference: constant lvalue reference problem
C universal reference: constant lvalue reference problem

Time:01-06

 

The class Test {
Public:
Static int count;
Public:
The Test ()=default;
The Test (int s);
The Test (const Test& Test)=delete;
The Test (Test& & Test).
Test& Operator=(const Test& Test)=delete;
Test& Operator=(Test& & Test).
To Test ();
Private:
Int size;
Int * PTR.
};

The Test: Test (int s) {
Size=s;
PTR=new int [s].
count++;
}

The Test: Test (Test& & Test) : the PTR (test. PTR), size (test. The size) {
Cout & lt; <"Move the copy constructor is called \ n";
}


Test& The Test: : operator=(Test& & Test) {
If (this==& amp; Test) {
return *this;
}
If (PTR! Nullptr)={
The delete [] PTR.
PTR=nullptr;
}
Size=test. The size;
PTR=test. PTR;
Test. The PTR=nullptr;
return *this;
}

The Test: : ~ Test () {
The delete [] PTR.
}

Int Test: : count=0;
Vector Vec.
Void func_test (vector & & Other) {
//vector Vec.
Vec. Push_back (STD: : move (other [0]));
}


Int main (int arg c, const char * argv []) {
//insert code here...

STD: : list L={,1,421.2, 2-2,53,4,1234,14,11345,12,43,1.1};
Vector Vec.
Vector Vec1;
Vec1. Push_back (move (Test (1)));
Func_test (move (vec1));
//auto ans=quick_sort (l);

return 0;
}


When the func_test ginseng to const vector & Other, the vec. Push_back invokes the Test copy constructor, didn't change before the call is move constructor, what reason is this excuse me

CodePudding user response:

This is the perfect forward
Void push_back (const _Ty & amp; _Val) {//insert element at the end, dojo.provide strong guarantee
Emplace_back (_Val);
}

Void push_back (_Ty & amp; & _Val) {//insert by moving into element at the end, dojo.provide strong guarantee
Emplace_back (_STD move (_Val));
}

CodePudding user response:

reference 1/f, the truth is more important than right or wrong response:
this is the perfect forward
Void push_back (const _Ty & amp; _Val) {//insert element at the end, dojo.provide strong guarantee
Emplace_back (_Val);
}

Void push_back (_Ty & amp; & _Val) {//insert by moving into element at the end, dojo.provide strong guarantee
Emplace_back (_STD move (_Val));
}

That how to change to the func_test function into the universal reference for ginseng, push_back call mobile constructor

CodePudding user response:

The first thing you need to understand what is mobile what is a copy?
  • Related