using namespace std;
class test {
public:
int p;
test() {
cout << "base" << endl;
}
test(int x) {
p = new int;* p = x;
cout<<"args" << endl;
}
test(test & args) {
p = new int;
*p = *(args.p);
cout<<“acopy”<< endl;
}
};
void print(test arg){
cout <<"funval"<< *(arg.p);
}
void printref(test & arg) {
cout <<“funref”<< *(arg.p);
}
int main()
{
test tl;
test t2 {10};
test t3 = t2;
print(t3);
printref(t2);
vector < test > myvec;
myvec.push_back(t2);
return 0;
}
Hello,
New to c++ here. I am trying to understand the calls of copy constructor with the code below.
My understanding seemed to be be correct till I created a vector of my class test.
When I run the below code , I run into error for line - myvec.push_back(t2)
Error 1:
/usr/include/c++/6/bits/stl_construct.h:75:7: error: invalid initialization of non—const reference of type test&' from an rvalue of type 'test'
Error2:
/usr/include/c++/6/ext/new_allocator.h:120:4: error: b inding 'const test' to reference of type 'test&' disca rds qualifiers { ::new((void *) p) _Up(std::forward<_Args>( args).
I read few articles here and I seem to have found the solution too, as below : Change for copy constructor Test(const test&args)
The thing I am unclear about is the description of errors generated .
In error1 , it says about rvalue. In my pushback call,t2 is an l-val not r-val. Correct? So,which r-val does error talk about?
I also read about push_back call.it’s syntax is: void push_back (const value_type& val); This expects a const type value and I am passing a non-constant which is ok. But I assume, push_back behind the pictures calls copy constructor and then a const value is passed to a non const argument in copy constructor and hence the error?
Can you please help me clarify my understandings here?
Thanks.