简体   繁体   English

在 C++11 中重置结构值

[英]Reset struct values in C++11

Looks like this question has been asked a few times but I can't seem to get it working based on existing answers and guidance.看起来这个问题已经被问过几次了,但我似乎无法根据现有的答案和指导来解决它。

Here's the code:这是代码:

#include <atomic>

class X
{
  public:
    X();
    ~X();
    void alpha();
  private:
    struct A {
      bool m;
      std::atomic<bool> n;
      bool fish();
    };
    A aval_;
};

X::X() : aval_() {}
X::~X() {}

bool X::A::fish() {
  return true;
}

void X::alpha() {
  aval_.m = false;
  aval_ = {};
}

Object of type 'X::A' cannot be assigned because its copy assignment operator is implicitly deleted无法分配类型为“X::A”的对象,因为其复制赋值运算符已隐式删除

Should I be overriding something?我应该覆盖某些东西吗? I am not generally a C++ programmer so feel free to point me to resources where I can learn more.我通常不是 C++ 程序员,因此请随时向我指出可以了解更多信息的资源。

EDIT: Updated the source code to include std::atomic<bool> .编辑:更新源代码以包含std::atomic<bool>

The reason is because std::atomic does not have a default copy-constructor.原因是std::atomic没有默认的复制构造函数。 Try the following code:试试下面的代码:

std::atomic<bool> v1(false);
std::atomic<bool> v2  = v1;

The errors you should get are:你应该得到的错误是:

error: call to implicitly-deleted copy constructor of 'std::atomic<bool>'
    std::atomic<bool> n2  = n1;
                      ^     ~~
note: copy constructor of 'atomic<bool>' is implicitly deleted because base class '__atomic_base<bool>' has a deleted copy constructor

note: '__atomic_base' has been explicitly marked deleted here
    __atomic_base(const __atomic_base&) = delete;

If the sole purpose of this is to reset the members of A , then simply create a reset function void reset() and reset the members to their initial values.如果这样做的唯一目的是重置A的成员,那么只需创建一个重置函数void reset()并将成员重置为其初始值。

void reset()
{
    m = false;
    n = false;
}

and then in void alpha() do:然后在void alpha()执行:

void alpha()
{
    aval.m = false;
    aval.reset();
}

The above is Plan A .以上是A计划 As Plan B , you can use a smart pointer ( std::unique_ptr ) to hold aval .作为Plan B ,您可以使用智能指针 ( std::unique_ptr ) 来保存aval Then you can simply reset the pointer.然后你可以简单地reset指针。

So instead of using the stack:所以不要使用堆栈:

A aval;

You use the heap:您使用堆:

    ...
    std::unique_ptr<A> aval;

public:
    X() : aval(std::make_unique<A>())
    {;}

    void alpha()
    {
        aval->m = false;
        aval.reset(new A());
    }

I personally like the first approach.我个人喜欢第一种方法。 Consider the fact that, regardless of its' name "constructor", a constructor constructs nothing.考虑这样一个事实,无论其名称为“构造函数”,构造函数都不会构造任何内容。 All it does is initialize the members of the class.它所做的只是初始化类的成员。 That's exactly what the reset() does, and you use the stack.这正是reset()所做的,并且您使用堆栈。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM