How to enforce move semantics when a vector grows?(当向量增长时如何强制执行移动语义?)
问题描述
I have a std::vector
of objects of a certain class A
. The class is non-trivial and has copy constructors and move constructors defined.
std::vector<A> myvec;
If I fill-up the vector with A
objects (using e.g. myvec.push_back(a)
), the vector will grow in size, using the copy constructor A( const A&)
to instantiate new copies of the elements in the vector.
Can I somehow enforce that the move constructor of class A
is beging used instead?
You need to inform C++ (specifically std::vector
) that your move constructor and destructor does not throw, using noexcept
. Then the move constructor will be called when the vector grows.
This is how to declare and implement a move constuctor that is respected by std::vector
:
A(A && rhs) noexcept {
std::cout << "i am the move constr" <<std::endl;
... some code doing the move ...
m_value=std::move(rhs.m_value) ; // etc...
}
If the constructor is not noexcept
, std::vector
can't use it, since then it can't ensure the exception guarantees demanded by the standard.
For more about what's said in the standard, read C++ Move semantics and Exceptions
Credit to Bo who hinted that it may have to do with exceptions. Also consider Kerrek SB's advice and use emplace_back
when possible. It can be faster (but often is not), it can be clearer and more compact, but there are also some pitfalls (especially with non-explicit constructors).
Edit, often the default is what you want: move everything that can be moved, copy the rest. To explicitly ask for that, write
A(A && rhs) = default;
Doing that, you will get noexcept when possible: Is the default Move constructor defined as noexcept?
Note that early versions of Visual Studio 2015 and older did not support that, even though it supports move semantics.
这篇关于当向量增长时如何强制执行移动语义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:当向量增长时如何强制执行移动语义?
基础教程推荐
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 设计字符串本地化的最佳方法 2022-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- C++,'if' 表达式中的变量声明 2021-01-01
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01