简体   繁体   中英

move constructor - is `new A()` rvalue?

struct Ex
{
    Ex()
    {
        std::cout<<"Default"<<std::endl;
    }

    Ex(const Ex &obj)
    {
        std::cout<<"Copy"<<std::endl;
    }

    Ex(Ex &&obj)
    {
        std::cout<<"Move"<<std::endl;
    }
};

int main()
{
   std::vector<Ex*> myVector;
   myVector.push_back( new Ex() );
}

Output: Default

Is new Ex() not a rvalue? Why is only default constructor getting called?

When you do

myVector.push_back( new Ex() );

You call the default constructor Ex::Ex() with new Ex() , which creates a new object on the heap. Then you only push the pointer to this new object to vector, not the object itselt. That means only the pointer is copied, not the object it's pointing to. Thus, there is no need to call any copy-constructor.

You can get the desired behaviour when using actual object instead of just pointers:

int main()
{
// no pointer VVVV
   std::vector<Ex> myVector;
   myVector.push_back( Ex{} );
}

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