0

这就是我所拥有的:

class A {
    class B{
        A* owner;
        B(A* owner){
            this->owner = owner;
        }
        B(B&& second)
            : owner(std::move(second.owner));
        {}

        B& operator=(B&& second){
            this->owner = second.owner;
        }
    };

    B* object;
    int a;
    string b;

    A(int a, string b){
        this->a = a;
        this->b = b;
        object = nullptr;
    }

    void create_B(){
        if(object == nullptr)
            object = new B(this);
    }

    A& operator=(A&& second){
        this->a = second.a;
        this->b = second.b;
        this->object = std::move(second.object);
        second.object = nullptr;
        return *this;
    }

    A(A&& second)
        : a(second.a)
        , b(second.b)
        , object(std::move(second.object)){
        second.object = nullptr;
    }
};

现在困扰我的是,当我做这样的事情时:

A a1(2, "aaa"), a2(3, "bbb");
a1.create_B();
swap(a1, a2);

一切都改变了它正确的位置(A的移动和移动赋值构造函数被正确调用)但B的所有者没有改变(虽然我希望它改变为a2,因为我们交换了)。

为什么这里不调用 B 的移动构造函数/移动赋值构造函数?提前致谢!

4

2 回答 2

0

Because the field object is moved (copied) as a pointer.

于 2013-11-07T19:55:16.883 回答
0

B's move constructor is not being called because you are moving a B* (pointer to B), not a B. Try defining object to be an instance of B.

于 2013-11-07T19:55:44.260 回答