1

我正在研究C++11移动构造函数,但有些东西不起作用。事实上,这个问题甚至在我开始编写这样的构造函数之前就已经存在。这是一段代码:

#include <iostream>
#include <string>
#include <sstream>

class Object {
    static std::ostream& log(Object &obj) {
        std::cout << "Object::id = " << obj.mId << "::"; 
        return std::cout;
    }

    unsigned mId = 0;
    std::string *mText = nullptr;

    unsigned nextUniqueId() const {
        static unsigned id = 0;
        return ++id;
    }

    const std::string textInfo() const {
        std::ostringstream oss;
        oss << "mText @ " << &mText;
        if (mText) oss << " = " << *mText;

        return oss.str();
    }

public:
    Object() = delete;
    Object& operator= (const Object&) = delete;

    explicit Object(const std::string& str) : mId(this->nextUniqueId()), mText(new std::string(str)) {
        Object::log(*this) << "constructor::one-argument\n";
    }

    Object(const Object& obj) : mId(this->nextUniqueId()), mText(new std::string(*obj.mText)) {
        Object::log(*this) << "constructor::copy\n";
    }

    virtual ~Object() {
        Object::log(*this) << "destructor::" << this->textInfo() << "\n";
        if (mText) {
            delete mText;
            mText = nullptr;
        }
    }
};

static Object get_object() {
    return Object("random text");
}

int main(int argc, char **argv) {
    Object a("first object");  // OK

    /*
     * Expected behaviour: inside get_object() function new Object is created which is then   copied into
     * variable b. So that new ID should be given.
     */
    Object b = get_object();  // What the hell?! Not what expected! Why?

    std::cout << std::endl;
    return 0;
}

预期的输出与此类似:

Object::id = 1::constructor::one-argument    
Object::id = 2::constructor::one-argument
Object::id = 2::destructor::mText @ 0x7fff32c25f70 = random text
Object::id = 3::constructor::copy

Object::id = 3::destructor::mText @ <DIFFERENT THAN IN ID=2> = random text
Object::id = 1::destructor::mText @ 0x7fff32c25f90 = first object

我得到了这个:

Object::id = 1::constructor::one-argument
Object::id = 2::constructor::one-argument

Object::id = 2::destructor::mText @ 0x7fff32c25f70 = random text
Object::id = 1::destructor::mText @ 0x7fff32c25f90 = first object

看起来变量b是在现场创建的(inline可能是什么?)。坦率地说,我不知道发生了什么,谁能解释一下?

4

3 回答 3

3

这称为返回值优化或 RVO。编译器选择get_object()直接在 in 的内存位置创建由 直接返回b的临时main。它受到标准和非常常见的优化的认可。

于 2013-08-12T18:40:41.337 回答
3

编译器优化了复制/移动就是......

于 2013-08-12T18:37:32.110 回答
1

允许编译器应用“返回值优化”RVO,这就是优化副本的原因。请注意,尽管存在与输出消息相关的副作用,但标准允许这样做

于 2013-08-12T18:39:40.923 回答