首页 > 系统相关 >如何在STL容器内存储对象的引用

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

时间:2022-11-10 16:34:20浏览次数:47  
标签:容器 存储 obj STL list Value int 对象 gfg

示例代码:

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里面对象中内容也发生改变。

标签:容器,存储,obj,STL,list,Value,int,对象,gfg
From: https://www.cnblogs.com/rayfloyd/p/16877530.html

相关文章