std::move 构造后对象的状态

发布于 2024-10-08 21:01:41 字数 496 浏览 2 评论 0原文

为了移动构造而移动的对象处于只能被销毁的状态,这是合法/正确的 c++0x 吗?例如:

class move_constructible {...};

int main()
{
    move_constructible x;
    move_constructible y(std::move(x));
    // From now on, x can only be destroyed. Any other method will result
    // in a fatal error.
}

为了记录,我试图用一个指针成员包装一个 C++ 类 ac 结构,该指针成员总是应该指向某个分配的内存区域。所有 C 库 API 都依赖于这个假设。但是这个要求阻止了编写真正便宜的移动构造函数,因为为了使 x 在移动后保持有效对象,它将需要自己分配的内存区域。我以这样的方式编写析构函数:在从 c API 调用相应的清理函数之前,它会首先检查 NULL 指针,这样至少可以在移动后安全地销毁该结构。

Is it legal/proper c++0x to leave an object moved for the purpose of move-construction in a state that can only be destroyed? For instance:

class move_constructible {...};

int main()
{
    move_constructible x;
    move_constructible y(std::move(x));
    // From now on, x can only be destroyed. Any other method will result
    // in a fatal error.
}

For the record, I'm trying to wrap in a c++ class a c struct with a pointer member which is always supposed to be pointing to some allocated memory area. All the c library API relies on this assumption. But this requirement prevents to write a truly cheap move constructor, since in order for x to remain a valid object after the move it will need its own allocated memory area. I've written the destructor in such a way that it will first check for NULL pointer before calling the corresponding cleanup function from the c API, so that at least the struct can be safely destroyed after the move.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

骄傲 2024-10-15 21:01:41

是的,语言允许这样做。事实上,这是移动语义的目的之一。然而,您有责任确保没有其他方法被调用和/或提供正确的诊断。请注意,通常您还可以至少使用赋值运算符来“恢复”变量,例如交换两个值的经典示例。

另请参阅此问题

Yes, the language allows this. In fact it was one of the purposes of move semantics. It is however your responsibility to ensure that no other methods get called and/or provide proper diagnostics. Note, usually you can also use at least the assignment operator to "revive" your variable, such as in the classical example of swapping two values.

See also this question

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文