Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Moving variables that are not pointers?

My question is that if we want to move an object and inside that object the variable we want to move is not a pointer, how should we release the temporary value?

Should I assign the memory of the temporary variable to nullptr? (Which is not even possible)

Here is the code for better understanding

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class Foo
{
public:
    ...

    Foo(Foo&& other) noexcept
    {
        m_Value = other.m_Value;

        /*
        The bottom line will not work, so what should I do instead of this line of code?
        */
        &other.m_Value = nullptr;
    }
private:
    int m_Value;
};

>Solution :

In your Foo move constructor, you are trying to set the moved-from object’s m_Value to nullptr, which is not valid since m_Value is not a pointer type. In fact, m_Value is an int type, which is a value type, meaning its value is stored directly inside the object.

In this case, you don’t need to release any memory because you are not dealing with pointers or dynamically allocated memory. When you move an object, the source object is typically left in a valid but unspecified state, which means you don’t need to worry about its internal state as long as it can be destroyed properly.

In your case, the default destructor will be sufficient to release any resources held by the Foo object, and you don’t need to set other.m_Value to any specific value.

Therefore, you can simply remove the line &other.m_Value = nullptr; from your move constructor, and your code will be correct.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading