开发者

Vector of objects that contain references

I have the following struct:

struct Transaction {
    Transaction(Book& bb, Patron& pp, Date dd)
        : b(bb), p(pp), d(dd) { }
        Book& b;
        Patron& p
        Date d;
};

When I try to put an object of type Transaction into a vector&开发者_JAVA百科lt;Transaction>v_t with a push_back, it won't work. A screenful of errors breaks lose.

Is it because I have references as members of my object?


You'll need an assignment and copy operator for the type since it contains a reference. STL container objects must be copyable AND assignable (and this won't be possible with your reference unfortunately).

Check this thread:

http://cboard.cprogramming.com/cplusplus-programming/106779-copy-constructor-class-const-reference-member.html

It discusses the problem and some alternate solutions, though it basically says don't have a reference member in container type.


STL is value-based and doesn't play well with references. You can get into a horrible tangle trying to get around this rule.

Turn the b, p, d members into values or shared_ptrs.


STL doesn't work with references because you can't have assignment operator that will assign a reference(not copy).
You should use pointers instead like:

struct Transaction {
    Transaction(Book& bb, Patron& pp, Date dd)
        : b(&bb), p(&pp), d(dd) { }
        Book* b;
        Patron* p
        Date d;
};


Community wiki, because this almost certainly invokes UB.

If you have a copy constructor you can make an assignment operator using placement new:

struct Transaction {
  Transaction(Book& bb, Patron& pp, Date dd)
    : b(bb), p(pp), d(dd) { }

  Transaction(const Transaction & src)
    : b(src.b), p(src.p), d(src.d) { }

  Transaction & operator= (const Transaction & src) {
    if (this != &src) {
      this->~Transaction();
      Foo * copy = new (this) Transaction(src);
      return *copy;
    } else {
      return *this;
    }
  }

  Book& b;
  Patron& p
  Date d;

};

This might work with your computer, with your compiler, with a specific optimization setting. Then again, it might not. Or it might suddenly stop working when your operator system auto-updates the C++ ABI library. Or it might suddenly stop working when you deliver it to your customer who has a slightly different version of the C++ ABI library.

No matter how you cut it, changing a reference is undefined behavior.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜