向量、移动语义、Nothrow 和 G++ 4.7
vector, move semantics, nothrow and g++ 4.7
我编写了以下代码来理解移动语义。它在 g++-4.6 中按预期工作(即没有副本,只有移动),但在 g++-4.7.0 中则不然。我认为这是 g++-4.7.0 中链接中的一个错误,但这个链接说它不是 g++-4.7 中的错误。因此,正如我从上面的链接中了解到的那样,我制作了移动构造函数 nothrow,但它仍然只复制。但是,如果我使复制构造函数 nothrow,则只会发生移动。谁能解释一下?
#include <iostream>
#include <vector>
using namespace std;
struct S{
int v;
static int ccount, mcount;
S(){}
//no throw constructor
//S(nothrow)(const S & x){
S(const S & x){
v = x.v;
S::ccount++;
}
S(S&& x){
v = x.v;
S::mcount++;
}
};
int S::ccount = 0;
int S::mcount = 0;
int main(){
vector<S> v;
S s;
for(int i = 0; i < 10; i++) {
v.push_back(std::move(s));
}
cout << "no of moves = " << s.mcount << endl;
cout << "no of copies = " << s.ccount << endl;
return 0;
}
你如何"使移动构造函数 nothrow"?在 g++ 4.7 中,如果我用 noexcept
注释移动构造函数,那么您的示例只会移动:
S(S&& x) noexcept{ ... }
no of moves = 25
no of copies = 0
相关文章:
- new(std::nothrow) int[n] 抛出异常
- 使用未声明的标识符"nothrow";你是说"扔"吗?记忆
- std::make_shared 和 std::make_unique 有"nothrow"版本吗?
- Linux g++ new (std::nothrow) 确实有效
- 模板通过一个专门化同时接受throw和nothrow
- 处理"Thrown exception type is not nothrow copy constructible"警告
- 为什么std::nothrow在gcc(4.9)中没有按预期工作
- 运算符++()nothrow不编译
- 如何为析构函数指定nothrow异常说明符
- 默认析构函数nothrow
- new(std::nothrow)而不是new和错误处理
- 将函数声明为 __attribute__(nothrow) 和 'throw()' 有什么区别
- throw()(即__declspec(nothrow))在视觉C++中是否带来了真正的好处
- 向量、移动语义、Nothrow 和 G++ 4.7
- 如何使用new(std::nothrow)使构造函数失败
- 我似乎无法将MS泄漏检测器用于新表达式“new(std::nothrow)”.是这样吗
- 为什么新的std::nothrow版本没有被广泛使用
- 带nothrow选项的Operator new仍然会抛出异常
- Std::string not nothrow move可赋值或可比较
- 在extern C中使用_attribute__ ((nothrow))有意义吗?