从内部范围内的对象到外部范围使用 C++ 的 std::move 是否安全?
Is it safe to use C++'s std::move from object in inner scope to outer scope?
在下面的 C++11/14 代码片段中,我使用 std::move
来
"move" vector Y
内部范围内的内容,到vector X
在外部范围内:
void foo() {
vector<int> X(10);
...
for (...) {
vector<int> Y(100);
...
X = std::move(Y);
}
...Safe to use X here which contains Y's last content?
}
Y
的 contructor/destructor 在每次迭代的循环 top/bottom 处被调用。由于内容是 Y
到 X
之外的 "moved",因此这些内容在循环结束后仍然可用(现在存储在 X
中)对吗?
是的,向量遵循值语义。
移动后,存储空间现在归外部向量所有。
在下面的 C++11/14 代码片段中,我使用 std::move
来
"move" vector Y
内部范围内的内容,到vector X
在外部范围内:
void foo() {
vector<int> X(10);
...
for (...) {
vector<int> Y(100);
...
X = std::move(Y);
}
...Safe to use X here which contains Y's last content?
}
Y
的 contructor/destructor 在每次迭代的循环 top/bottom 处被调用。由于内容是 Y
到 X
之外的 "moved",因此这些内容在循环结束后仍然可用(现在存储在 X
中)对吗?
是的,向量遵循值语义。
移动后,存储空间现在归外部向量所有。