gpt4 book ai didi

c++ - 运算符 + 需要移动构造函数

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

我无法编译附加项目,因为我删除了移动构造函数。

这是预期的行为吗?如果编译器不使用它,为什么它需要移动构造函数?

windows-visual studio 2015 14.0.25431.01 update3

#include <string>
#include <sstream>
#include <vector>

class poo {
public:
poo() = default;
poo(poo&&) = delete; //deleted function
virtual ~poo() = default;

poo operator +(const poo &a) const {
poo to_return;
to_return._s += a._s;
return to_return;
//moveconstructors.cpp(14): error C2280: 'poo::poo(poo &&)': attempting to reference a deleted function
}
private:
std::string _s;
};

int main(int, char **) {
poo a;
return 0;
}

编辑 1:添加“poo (const poo &) = default;”后会出现相同的结果

编辑 2:同样的结果发生在 windows-visual studio 2019 16.1.0 preview 2.0

编辑 3:添加/修改后发生相同的结果

  poo(const std::string &s) : _s(s) {
}
poo operator +(const poo& a) const {
return poo(_s + a._s);
}

编辑 4:它适用于 vs2019 和/std:c++17

最佳答案

poo(poo&&) = delete;

这一行禁用了移动构造函数,是的,但它删除了复制构造函数。

来自 class.copy.ctor:

If the class definition does not explicitly declare a copy constructor, a non-explicit one is declared implicitly. If the class definition declares a move constructor or move assignment operator, the implicitly declared copy constructor is defined as deleted;.

现在,如果 named return value optimization (NRVO) 这一切都不是什么大问题由标准保证,因为编译器可以看到您的 operator+ 有一个局部变量的返回。在那种情况下,我们不需要复制或移动构造函数; poo 实例将被创建并通过引用传递给 fn(“幕后”)。

请注意,在 C++17 中,您可以使用保证复制省略 (RVO) 来解决此问题:

poo(std::string s) : _s(std::move(s)){}

poo operator +(const poo &a) const {
return poo(_s + a._s);
}

Demo

但是,即使在 C++20 中,named 返回值优化仍无法保证。允许实现使用移动操作。

[class.copy.elision] 指出:

In the following copy-initialization contexts, a move operation might be used instead of a copy operation:
- If the expression in a return statement is a (possibly parenthesized) id-expression that names an object with automatic storage duration declared in in the body or parameter-declaration-clause of the innermost enclosing function or lambda-expression

关于c++ - 运算符 + 需要移动构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57167209/

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