0
#include <iostream>
#include <stdio.h>

class Stack{

public:
    Stack(int size):msize(size){
        std::cout << "Stack::Stack() called" << std::endl;
    }
    
    // Constructor 2: Copy constructor with non-const lvalue reference
    Stack(Stack &src)
    :msize(src.msize)
    {
    std::cout << "Stack::Stack(const Stack&)" << std::endl;
    }

    // Constrcutor 3: Move constructor with rvalue reference
    Stack(Stack &&src)
        :msize(src.msize)
    {
        std::cout << "Stack::Stack(Stack&&)" << std::endl;
    }

    ~Stack()
    {
    std::cout << "~Stack()" << std::endl;
    }

    Stack& operator=(const Stack &src)
    {
        std::cout << "operator=" << std::endl;
        if (this == &src)
            return *this;

        return *this;
    }

    Stack& operator=(Stack &&src)
    {
        std::cout << "operator=&&" << std::endl;
        if (this == &src)
            return *this;

        return *this;
    }

    int getSize() 
    {
        return msize;
    }
  
private:
    int msize;
};


Stack GetStack(Stack &stack)
{
    Stack tmp(stack.getSize());
    std::cout << "tmp is created" << std::endl;
    return tmp;
};

int main(){
    
    Stack s(100);
    std::cout << "s is created" << std::endl;
    
    s = GetStack(s);
    
    return 0;
}

I define 3 constructors in Stack class. If I run the main function without any change, then when the tmp object(which is declared in GetStack()) is returned, the compiler will call constructor 3(which is a move constructor) to create a temporary and then return. So under this circumstance, I initially think the ready-to-return object tmp is a rvalue.

But when I comment the code snippet of Constructor 3 and re-run the code, the compiler just calls constructor 2 to create a temporary, so when the move constructor does not exist, tmp is treated as lvalue.

So my question is that is tmp a rvalue or a lvalue when it is ready to return from GetStack(). My compile option is g++ -fno-elide-constructors -o ref ref.cpp

Zijian XU
  • 11
  • 2
  • Objects are not lvalues or rvalues. Value category is a property of expressions, not of objects. An id-expression referring to a local variable used as operand to a `return` statement is special and will be treated as xvalue when possible or lvalue otherwise. I will try to find a duplicate. – user17732522 Oct 20 '22 at 02:24

0 Answers0