gpt4 book ai didi

c++ - vector 、 move 语义、nothrow 和 g++ 4.7

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:31:12 26 4
gpt4 key购买 nike

我编写了以下代码来理解 move 语义。它在 g++-4.6 中按预期工作(即没有复制,只 move ),但在 g++-4.7.0 中没有。我认为这是 g++-4.7.0 中链接的错误,但这个 link说这不是 g++-4.7 中的错误。因此,正如我从上面的链接中理解的那样,我使 move 构造函数不抛出,但它仍然只执行复制。但是,如果我不抛出复制构造函数,则只会发生 move 。谁能解释一下?

#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;
}

最佳答案

您如何“使 move 构造函数不抛出”?对于 g++ 4.7,如果我用 noexcept 注释 move 构造函数,那么您的示例只会 move :

S(S&& x) noexcept{ ... }

no of moves = 25
no of copies = 0

关于c++ - vector 、 move 语义、nothrow 和 g++ 4.7,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10241182/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com