C++ unexpected behaviour (where are my temporaries!?)

后端 未结 4 1631
长发绾君心
长发绾君心 2020-12-19 11:40

This was an r-value experiment but it mutated when gcc whined to me about lack of move-constructor (I\'d deleted it) and didn\'t fall-back to the copy constructor (as I expe

4条回答
  •  南方客
    南方客 (楼主)
    2020-12-19 12:06

    To prevent copy illision implement the assignment operator with the copy/swap algorithm like:

    Object &operator =(Object other)
    {
        std::swap(*this, other);
        return *this;
    }
    

    And then try:

    Object a;
    a = test();
    

    That way the copy (or move) ctor will be called by the compiler when it passes the object into the assignment operator.

提交回复
热议问题