简体   繁体   中英

Move semantics with LValue reference

So Move semantics is great, giving us higher performence.

I read this was a completly new feature and without C++11 it is 'impossible' to do this.

But could we do this before C++11? Like something that goes like the below.

class AAA
{
private:
    int* m_data;
public:
    AAA(int _data) : m_data(new int(_data)) { }
    AAA(AAA& _other) // Not using RValue reference.
    {
        m_data = _other.m_data;
        _other.m_data = nullptr;
    }

    ~AAA() { delete m_data; }
};

int main()
{
    AAA sth1(100);
    AAA sth2(sth1)
    return 0;
}

I thought that what the existence of RValue reference is for is not to make the same functions whose argument is just slighty different(like Const and Non-Const).

Simply, with RValue reference which is just another 'type', we can do both Copy constructor and Move constructor at the same time. And that's it.

Wondering if I am correct or am missing something huge.

Thanks in advance.

std::auto_ptr did exactly what you suggest. The problem was that it made behavior confusing and copying impossible. Rvalue references allow one to make classes that can be both moved and copied.

rvalue references allow automatic moving/copying based upon context (for example the moving of a temporary) trying to simulate this with an lvalue style copy constructor (which actually performed a move) would likely be disastrous.

My understanding is that move semantic is not only possible but also available as library ( Boost.Move ) for C++03 compilers (maybe with some restrictions). However, the language implementation might have been necessary both to allow free optimization without touching anycode and to simplify it's use as much as possible.

Yes, there is something missing, which you do not get with lvalues, even if they are non const. Non const lvalues cannot be produced from temporaries, so your attempt does not work in that case.

What if you want to pass an rvalue to your constructor? Your ctor will fail because it's non-const. With rvalue references, you can pass an rvalue to the ctor, and move from it, as rvalues are always temporaries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM