从STL容器移动元素是否从该容器中移除它?

Bre*_*hns 4 c++ stl visual-studio-2010 move-semantics

我有一个Foobar类的sayHello()方法,输出"嗯,你好!".如果我写下面的代码

vector<unique_ptr<Foobar>> fooList;
fooList.emplace_back(new Foobar());

unique_ptr<Foobar> myFoo = move(fooList[0]);
unique_ptr<Foobar> myFoo2 = move(fooList[0]);
myFoo->sayHello();
myFoo2->sayHello();

cout << "vector size: " << fooList.size() << endl;
Run Code Online (Sandbox Code Playgroud)

输出是:

Well hello there!
Well hello there!
vector size: 1
Run Code Online (Sandbox Code Playgroud)

我很困惑为什么这样做.fooList[0]我做第一步时不应该变为空吗?为什么myFoo2工作?

这是Foobar看起来像:

class Foobar
{
public:
    Foobar(void) {};
    virtual ~Foobar(void) {};

    void sayHello() const {
        cout << "Well hello there!" << endl; 
    };
};
Run Code Online (Sandbox Code Playgroud)

Mik*_*our 12

当我第一次移动时,fooList [0]不应该变为null吗?

是.

为什么myFoo2有效?

它没有; 它会导致未定义的行为.如果使用空指针调用非解除引用的非虚函数,则编译器会生成不会崩溃的代码this.

如果您按如下方式更改功能,则会更清楚地发生了什么:

void sayHello() const {
    cout << "Well hello there! My address is " << this << endl; 
}

Well hello there! My address is 0x1790010
Well hello there! My address is 0
vector size: 1
Run Code Online (Sandbox Code Playgroud)