gpt4 book ai didi

c++ - 从 STL 容器中 move 元素是否会将其从该容器中移除?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:05:03 24 4
gpt4 key购买 nike

我有一个 Foobar 类,它带有一个输出“Well hello there!”的 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;

输出是:

Well hello there!
Well hello there!
vector size: 1

我很困惑为什么会这样。当我迈出第一步时,fooList[0] 不应该变成 null 吗?为什么 myFoo2 有效?

这是 Foobar 的样子:

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

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

最佳答案

Shouldn't fooList[0] become null when I do the first move?

是的。

Why does myFoo2 work?

它没有;它会导致未定义的行为。如果您使用空指针调用不取消引用 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

关于c++ - 从 STL 容器中 move 元素是否会将其从该容器中移除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8974418/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com