如何在STL容器内存储对象的引用

示例代码:

class gfg {
 private:
  int a;
  gfg(const gfg&) = delete;
  gfg& operator=(const gfg&) = delete;

 public:
  explicit gfg(int a) { this->a = a; }
  void setValue(int a) { this->a = a; }
  int getValue() { return this->a; }
};

int main() {
  // Declare list with reference_wrapper
  std::list<std::reference_wrapper<gfg> > l;

  // Object of class gfg
  gfg obj(5);

  l.push_back(obj);

  // Print the value of a
  std::cout << "Value of a for object obj is " << obj.getValue() << std::endl;

  std::cout << "After Update" << std::endl;

  // Change the value of a for Object obj
  // using member function
  obj.setValue(700);

  // Print the value of a after Update
  std::cout << "Value of a for object obj is " << obj.getValue() << std::endl;

  std::cout << "\nValue stored in the list is ";
  for (gfg& i : l) std::cout << i.getValue() << std::endl;
}

运行结果:

Value of a for object obj is 5
After Update
Value of a for object obj is 700

Value stored in the list is 700

 

结论: 

obj对象并没有被复制,而且通过obj改变对象内容后,vector里面对象中内容也发生改变。
posted @ 2022-11-10 16:28  Ray.floyd  阅读(54)  评论(0编辑  收藏  举报