CPP link in constructor and function

Confuse the code below a bit. `

class sample
{
     public:
     sample() {  }
     sample( sample& Obj ) {  }
 };

void fun( sample& Obj ) {   }

int main()
{
    sample s(sample());
    fun( sample() );
    return 0;
}

we get the following error

Compilation error due to the following errors (errors). main.cpp: In the function 'int main ()': main.cpp: 29: 19: error: invalid initialization of a non-constant reference of type 'sample &' from a value of type 'sample' fun (sample ());

I figured changing the argument in the fun from & obj to const sample & obj will resolve the error.

My question is, even for the copy constructor, a temporary object has also been sent. But why the compiler did not throw the same error.

Good explanation welcomed

Relations Prasat S.

+4
source share
2 answers

This line:

sample s(sample());

s, - , , . . " ". .

, , , . , , , . :

sample s(sample());

:

s.sampleMember = 1;

, s , . , :

sample s((sample()));

++ 11 - :

sample s(sample{});
+6

:

- " " :

sample s(sample());

. . sample s ((sample())) ++ 11 sample s (sample {}) .

, lvalue rvalue, , , :

fun( sample() );

:

void fun( const sample& Obj ) {   }

( ++ 11)

 void fun( sample&& Obj ) {   }

(, Obj fun), const lvalue rvalue rvalues. , , Obj , lvalue:

void fun(sample& Obj ) {   }

lvalue,

fun(s)
+3

Source: https://habr.com/ru/post/1694032/


All Articles