【问题标题】:Questions about vector, union, and pointers in C++C++中关于向量、联合、指针的问题
【发布时间】:2010-12-19 15:42:24
【问题描述】:

我的问题不是家庭作业问题,但我正在考虑在我的作业中使用这些概念。上下文(如果有帮助的话)是这样的:我需要跟踪几个联合实例,它们在我自己的一个类中属于我自己的联合,作为类变量。 (注意:联合实例的数量是未知的,所以我不能只拥有固定数量的联合实例。

  1. Q1:如果我有一个工会,比如 MyUnion, 以及这种联合的许多例子, 然后我可以将它们放入向量中吗 喜欢

    vector<union MyUnion> myVector(10);
    
  2. Q2:有一个指针是否有效 联盟?喜欢

    union MyUnion *myUnionPtr = new union myUnion;
    
  3. Q3:我正在考虑使用向量 我的联合指针 实现,是不是这个概念 正确的?还有,正常吗 C++ 中的方法?我需要吗 重新考虑我的设计?

【问题讨论】:

    标签: c++ pointers vector unions


    【解决方案1】:
    1. 如果联合是 CopyConstructable 和 Assignable,那么它满足 std::vector 的要求。
      • 是:MyUnion* ptr = new MyUnion();
      • 指针容器在某些情况下有效,但如果您想要一个拥有指针的容器,请查看 Boost 的 ptr_* containers。但是,在这里,您似乎要么拥有一个非指针容器,要么拥有一个非拥有指针容器,这两种方式都适用于矢量。

    默认情况下,所有类型都是 CopyConstructable 和 Assignable。 (“可复制”用于表示这些概念的联合,但标准单独指定它们。)这是因为复制ctors和op=被添加到类中(联合是一种类类型),除非在某些情况下。网上有几个references,但我不知道有哪一个可以在网上免费获得,说明这些。

    你必须竭尽全力阻止它,例如:

    • 复制 ctor 或 op= 非公开
    • 使复制 ctor 或 op= 采用非常量引用
    • 给类类型一个非CopyConstructable或非Assignable成员

    例子:

    union CopyableUnion {
      int n;
      char c;
      double d;
    };
    
    union NonCopyableUnion {
      int n;
      char c;
      double d;
    
      NonCopyableUnion() {} // required, because any user-defined ctor,
      // such as the private copy ctor below, prevents the supplied
      // default ctor
    
    private:
      NonCopyableUnion(NonCopyableUnion const&);
      NonCopyableUnion& operator=(NonCopyableUnion const&);
    };
    
    int main() {
      CopyableUnion a;
      CopyableUnion b = a; // fine, uses copy ctor
      b = a; // fine, uses op=
    
      NonCopyableUnion c;
      NonCopyableUnion d = c; // compile error (copy ctor)
      d = c; // compile error (op=)
    
      return 0;
    }
    

    注意: 仅仅因为某些东西是可复制的,并不意味着它会做你想做的事!示例:

    struct A {
      int* p;
    
      A() : p(new int()) {}
    
      // the provided copy ctor does this:
      //A(A const& other) : p(other.p) {}
      // which is known as "member-wise" copying
    
      ~A() { delete p; }
    };
    
    int main() {
      A a;
      {
        A b = a;
        assert(b.p == a.p); // this is a problem!
      } // because when 'b' is destroyed, it deletes the same pointer
      // as 'a' holds
    
      return 0; // and now you have Undefined Behavior when
      // ~A tries to delete it again
    }
    

    当然,工会也是如此。不过,该修复同样适用:

    struct A {
      int* p;
    
      A() : p(new int()) {}
    
      A(A const& other) : p(new int(*other.p)) {}
    
      ~A() { delete p; }
    };
    

    (如果你发现了它,是的,如果你尝试使用 op=,A 就会出现问题,就像它最初使用复制 ctor 的方式一样。)

    【讨论】:

    • 如何确定联合是否可复制和可分配?
    • @derrdji:我认为只要所有成员都是(不要明确否认)并且工会本身没有明确否认。
    猜你喜欢
    • 2014-05-13
    • 2021-09-10
    • 1970-01-01
    • 1970-01-01
    • 2023-01-08
    • 1970-01-01
    • 1970-01-01
    • 2011-02-01
    • 2018-10-02
    相关资源
    最近更新 更多