2

I've encountered a change in behaviour (at least to my understanding) between primitives and Classes i've created in c++. say, the following:

int foo()
{
    int a = 4;
    return a;
}

int main() 
{

    foo() = 2;
}

of course creates causes a compilation error, because i'm trying to assign somthing into an rvalue. But if i were to create my own class, say Complex, the following:

Complex foo()
{
    Complex a = Complex(2,4);
    return a;
}

int main() 
{

    foo() = Complex(1,2);
}

would actually work. I thought the only way for this to compile is if foo() returned a reference. What am i missing? i assume there is a difference between primitives and Classes - isn't the return value of Complex foo() an rvalue? Thanks!

Nir Sweed
  • 21
  • 1
  • @NathanOliver: you have to go home, maybe ? – Liviu Sep 27 '16 at 15:24
  • I guess what's happening is that your class has an [implicitly-defined move constructor](http://en.cppreference.com/w/cpp/language/move_constructor#Trivial_move_constructor), but a fundamental type doesn't. – Ami Tavory Sep 27 '16 at 15:26
  • Also see: http://stackoverflow.com/questions/15824750/c-function-returns-a-rvalue-but-that-can-be-assigned-a-new-value and http://stackoverflow.com/questions/34835686/rvalue-on-the-left-side – NathanOliver Sep 27 '16 at 15:27
  • @NathanOliver I'm not sure that those are exact duplicates. Those questions deal with the move constructors of user-defined types. This question contrasts the behavior of a primitive type with a user defined type. FWIW, I've been searching a few minutes, and couldn't find anything specific about a primitive type not having a move constructor. – Ami Tavory Sep 27 '16 at 15:33
  • @AmiTavory Primitives do not need to be moved as moving or copying them is the the same thing. This question though has nothing to do with moving. It is about trying to assign a value to an object that is return from a function my value. – NathanOliver Sep 27 '16 at 15:36

0 Answers0