移动语义和基元类型
Move semantics and primitive types
示例代码:
int main()
{
std::vector<int> v1{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
std::cout << "Printing v1" << std::endl;
print(v1);
std::vector<int> v2(std::make_move_iterator(v1.begin()),
std::make_move_iterator(v1.end()));
std::cout << "Printing v1" << std::endl;
print(v1);
std::cout << "Printing v2" << std::endl;
print(v2);
std::vector<std::string> v3{"some", "stuff", "to",
"put", "in", "the", "strings"};
std::cout << "Printing v3" << std::endl;
print(v3);
std::vector<std::string> v4(std::make_move_iterator(v3.begin()),
std::make_move_iterator(v3.end()));
std::cout << "Printing v3" << std::endl;
print(v3);
std::cout << "Printing v4" << std::endl;
print(v4);
}
输出:
Printing v1
1 2 3 4 5 6 7 8 9 10
Printing v1
1 2 3 4 5 6 7 8 9 10
Printing v2
1 2 3 4 5 6 7 8 9 10
Printing v3
some stuff to put in the strings
Printing v3
Printing v4
some stuff to put in the strings
问题
由于对基元类型的移动操作只是一个副本,我可以假设
v1
将保持不变吗?或者即使使用基元类型,状态也未指定吗?我假设基元类型没有移动语义的原因是因为复制同样快,甚至更快,这是正确的吗?
-
不,如果你想假设这一点,你应该复制,而不是移动。
-
移动会使源对象处于有效但未指定的状态。基元类型do表现出移动语义。源对象保持不变这一事实表明复制是实现移动的最快方法。
相关文章:
- 是否可以/希望创建不可复制的共享指针模拟(以启用weak_ptr跟踪/借用类型语义)?
- Eclipse/CDT_C++给出"语义错误_"类型XXX无法解决"。项目运行
- boost multi_index - 如果元素类型仅支持移动语义,如何遍历它?
- 标准库中是否有与 std::thread 的构造函数语义匹配的类型擦除函数包装器?
- Bison:将联合语义类型与C++解析器一起使用
- 移动 POD 类型的语义
- 解析问题:预期的不合格的ID和语义问题:C 需要所有声明的类型说明符
- 使用模板将语义从一种类型移动到另一种类型
- 移动语义:从"类型&&"到"类型"的转换无效。模板:将未知参数传递给重载函数
- 指向不可变类型的共享指针具有值语义
- 移动语义和基元类型
- 将语义与std::原子类型进行比较
- 检测Spirit语义动作中的参数类型
- xcode 构建错误:从指针到较小类型"int"的语义问题丢失了信息
- Boost spirit:使用语义动作和phoenix时的参数类型
- 关于类型移动语义的注意事项
- 最语义正确和类型安全的构造从序列化字节数组?(c++ 11)
- 编译器强制的语义类型
- 返回类型和移动语义
- Do内置类型具有移动语义