gpt4 book ai didi

c++ - 编译器何时应该生成 move 构造函数?

转载 作者:IT老高 更新时间:2023-10-28 22:34:51 25 4
gpt4 key购买 nike

我使用 VS11 并使用以下内容:

class ContextWrapper
{
public:

ContextWrapper()
{
} //it should be defaulted I *guess* in order to have automatic move constructor ?
// no support in VS11 for that now

Context* GetContext()
{
return this->context.get();
}

void SetContext(std::unique_ptr<Context> context)
{
this->context = std::move(context);
}

//ContextWrapper(ContextWrapper&& other): context(std::move(other.context))
//{
//} // I would like this to be generated by the compiler

private:
ContextWrapper(const ContextWrapper&);
ContextWrapper& operator= (const ContextWrapper&);

std::unique_ptr<Context> context;
};

我希望此类生成 move 构造函数/赋值。我没有一个微不足道的构造函数的事实是我没有得到 move 的原因吗?还是有其他因素影响?

最佳答案

不幸的是,C++11 的这一部分在不断变化。而且无论标准要说什么,VC11 都不可能实现它。所以就今天而言,我不相信你能指望生成的 move 成员。

不过,这是一个很好的问题,我想得到一个很好的答案。

一般来说,如果您没有用户声明的复制成员或析构函数,编译器应该生成 move 成员。 = default= delete 算作用户声明。如果您声明一个 move 成员(例如 move 构造函数),则不会隐式生成另一个。

不幸的是,C++11 继续说,有时 move 成员在使用 =default 声明时会被隐式删除,有时它们的生成取决于基类和成员是否具有 move 成员或微不足道可复制。这太复杂了,有时会产生令人惊讶的行为。这是跟踪此错误的 CWG 问题:

http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1402

在我撰写本文时,该问题没有正确的建议解决方案。我预计这会在大约一周内改变。在俄勒冈州波特兰举行的 2012 年秋季 C++ 标准 session 上,达成了一项协议(protocol),其内容基本上是:

  1. 编译器永远不会隐式删除 move 成员。
  2. move 成员的隐式生成将始终与 = default 相同。
  3. 隐式生成不会依赖于基础或成员的琐碎性,也不依赖于它们在 move 时是否会抛出。

简而言之,我希望 CWG 1402 的更正措辞简单地说:

In general, the compiler should generate move members if you have no user-declared copy members nor destructor. = default and = delete counts as user-declared. If you declare one move member (e.g. move constructor), the other will not be implicitly generated. And if you =default a move member, you'll get something that moves each base and member.

(适当的标准化)。我还没有看到会这样说的措辞。 Jason Merrill 正在为我们编写。

这意味着有时编译器会隐式生成 throw move 成员。但我们要的是简单的规则,但大多数时候都做正确的事(很少有惊喜)。

关于c++ - 编译器何时应该生成 move 构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13174973/

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