首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >向量、移动语义、nothrow和g++ 4.7

向量、移动语义、nothrow和g++ 4.7
EN

Stack Overflow用户
提问于 2012-04-20 14:16:29
回答 1查看 1.1K关注 0票数 5

我写了下面的代码来理解移动语义。它按照预期工作(即。在g++-4.6中没有拷贝,只有移动),但在g++-4.7.0中没有。我认为这是g++-4.7.0中链接的错误,但这个link显示它不是g++-4.7中的错误。因此,正如我从上面的链接中理解的那样,我创建了move构造函数nothrow,但它仍然只复制。但是,如果我将复制构造函数设为nothrow,则只有moves发生。有人能解释这一点吗?

代码语言:javascript
复制
#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;
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-04-20 14:34:05

你是如何“让移动构造器nothrow”的?在g++ 4.7中,如果我用noexcept注释move构造函数,那么您的示例只做moves:

代码语言:javascript
复制
S(S&& x) noexcept{ ... }

no of moves = 25
no of copies = 0
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10241182

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档