如何确保对象确实会从中移出? [英] How to make sure an object will really be moved from?

查看:75
本文介绍了如何确保对象确实会从中移出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码,该代码尝试移动构造shared_ptr,但是由于错误而似乎对其进行复制构造:

Consider the following code, which tries to move-construct a shared_ptr, but due to a mistake appears to copy-construct it:

#include <utility>
#include <cassert>
#include <memory>

int main()
{
    const auto x=std::make_shared<int>(4325); // can't be moved from
    const std::shared_ptr<int> y(std::move(x)); // silently copy-constructs
    assert(x==nullptr); // fails
}

在这里,由于xconst,所以只能在运行时检测到y是复制构造的,而不是移动构造的.有什么方法可以确保在编译时确实发生移动??

Here the fact that due to x being const, y was copy-constructed instead of move-construction will only be detected at runtime. Is there any way to make sure move really occurs, at compile time?

推荐答案

您可以编写一个检查器来查看是否可以从以下位置移动表达式:

You could write a checker to see if an expression could be moved from:

template <typename T>
constexpr bool can_be_moved (T&&) {
    return !std::is_reference<T>{} && !std::is_const<T>{};    
}

然后您可以static_assertstd::move(x)从以下位置移出:

Then you can static_assert that std::move(x) can be moved from:

int main()
{
    const auto x=std::make_shared<int>(4325);
    const std::shared_ptr<int> y(std::move(x));
    static_assert(can_be_moved(std::move(x)), "x must be able to be moved from");
}

我不太确定这在实践中是否有用.除非您知道该类的构造函数会做什么,否则您仍然无法保证一定会被真正删除.

I'm not really sure how useful this is in practice though. You still can't guarantee that something will truly be moved from unless you know what the constructors of the class do.

这篇关于如何确保对象确实会从中移出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆