将赋值移动到具有const值的对象 [英] move assignment to object with const value

查看:42
本文介绍了将赋值移动到具有const值的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的结构:

struct OBJ {
  int x;
  const int y;
  OBJ& operator=(OBJ &&oth)
  {
    y = oth.y; // this is disallowed
    return *this;
  }
}

还有示例代码

void func() {
  static OBJ obj;
  OBJ other; // random values
  if(conditon)
    obj = std::move(other); //move
}

我理解这是因为 obj 是具有常量成员 y 非const OBJ.我不能只更改y,但应该可以更改整个对象(调用析构函数和构造函数).这是可能的还是唯一正确的解决方案是在 y 之前删除我的 const ,并记住不要意外更改?

I understand this as obj is Non const OBJ with const member y. I can't change just y but I should be able to change whole object (call destructor and constructor). Is this possible or the only proper solution is to remove my const before y, and remember to don't change by accident?

我需要在 func 调用之间存储我的 static obj ,但是如果条件为真,我想将其他对象移动到此静态对象上.

I need to store my static obj between func call but if condition is true i want to move other object in place of this static object.

推荐答案

我建议改用 std :: unique_ptr :

void func() {
  static std::unique_ptr<OBJ> obj = std::make_unique<OBJ>();
  std::unique_ptr<OBJ> other = std::make_unique<OBJ>(); // random values
  if(condition)
    obj = std::move(other); //move
}

在许多情况下,这是您的选择,其中需要移动无法移动的内容,以容纳未知的多态类型,或者在任何其他无法处理实际类型的情况下.

This should be your choice in many cases where there is a need to move something that cannot be moved, to hold an unknown polymorphic type or any other case where you cannot deal with the actual type.

这篇关于将赋值移动到具有const值的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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