【问题标题】:dereferenced unique_ptr and changing values in struct doesn't stick取消引用的 unique_ptr 和更改 struct 中的值不会坚持
【发布时间】:2019-07-18 00:46:54
【问题描述】:

我正在努力学习 C++ 的基础知识,和每个人一样,学习指针很难。

所以,我正在尝试 C++14 std::unique_ptr 类,这可能是一个愚蠢的问题。

#include <iostream>
#include <memory>

struct Foobar {
    bool active = false;   
};

int main()
{
  std::unique_ptr<Foobar> foobar = std::make_unique<Foobar>();

  Foobar foo = *foobar;
  foo.active = true;

  Foobar bar = *foobar;

  // prints zero and not one
  std::cout << bar.active << std::endl;
}

取消引用我的指针并更改结构中的bool 不会更改内存中的实际基础值。为什么会这样?

我缺少什么基本的东西?

【问题讨论】:

  • Foobar foo = *foobar 复制存储在foobar中的对象到本地变量foo中,然后foo.active = true修改这个本地副本。相反,你需要引用它:Foobar&amp; foo = *foobar(或者你可以写foo-&gt;active = true)。
  • 我的评论打错了:我的意思是你可以写foobar-&gt;active = true

标签: c++ c++14 unique-ptr


【解决方案1】:
Foobar foo = *foobar;
foo.active = true;

这会复制foobar 引用的对象,并将其存储在一个名为foo 的新变量中;然后修改fooactive标志。

当然,这对(仍然)被foobar 引用的原始对象没有任何作用。

然后代码会制作另一个对象副本,并打印其active 标志的未修改值。

【讨论】:

  • 也许指出如何使这项工作(foobar-&gt;active = true;Foobar&amp; foo = *foobar; foo.active = true;)?
猜你喜欢
  • 1970-01-01
  • 2023-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-29
  • 2023-03-23
  • 2012-10-03
  • 1970-01-01
相关资源
最近更新 更多