Question

I'm trying to get a firm grasp on move and copy constructors and assignments.

I have the following simple templated class:

template<typename T>
class Box {

public:
    // Copy constructor
    explicit Box(const T& val) { 
        value = val; 
    }

    // Move constructor
    explicit Box(const T&& val) {
        value = val;
    }

    // Set and get value
    void set(T val) { value = val; }
    T get() { return value; }

    // Copy assignment operator
    T& operator=(const T& val) {
        value = val;
    }

    // Move assignment operator
    T& operator=(const T&& val) {
        value = val;
    }

private:
    T value;

};

Which is used by the following code:

int main() {
    Box<int> iBox{ 1 };

    int j = 5;
    Box<int> jBox{ j };

    iBox = jBox;

    return 0;
}

I would expect, if my code is correct, that when I step into iBox = jBox, I should step into one of the assignment overloads. Why is this not happening?

Was it helpful?

Solution

You have not declared an assignment operator taking a right-hand operand of type Box, so the compiler has no other option than to use its generated default assignment operator.

You also have no return statements in your assignment operators, by the way.

Maybe you meant to write:

Box& operator=(const Box& other) {
    value = other.value;
    return *this;
}

Box& operator=(Box&& val) {
    value = other.value;
    return *this;
}

Notice that an rvalue reference to const would make little sense.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top