c++ - vector 作为类成员

标签 c++ c++11

class A
{
   private:
      std::vector<int>myvec;
   public:
      const std::vector<int> & getVec() const {return myvec;}
};
void main()
{
   A a;
   bool flag = getFlagVal();
   std::vector<int> myVec;
   if(flag)
      myVec = a.getVec(); 
   func1(myVec);
}

myVec= a.getVec() 行中,有一个 vector 的拷贝,尽管它是通过引用返回的。如果 flag 不是 true,则会传递一个空 vector 。

无论如何要避免这个拷贝?

最佳答案

func1(flag ? a.getVec() : std::vector<int>());

是一种方式。

如果 func1 通过 const 引用获取 vector ,这将起作用,因为两个匿名临时对象都可以绑定(bind)到它。

关于c++ - vector 作为类成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66457048/

相关文章:

c++ - 两个字符串大小的差异

c++ - 如何正确 "perfect forward"getter 函数?

c++ - 使用枚举作为常量表达式。哪个编译器是正确的?

c++ - 使用 libpq 组织 PostgreSQL 数据库连接参数?

c++ - 另一个 "ISO C++ forbids declaration"错误

c++ - 得到错误的输出

c++ - 使用 cin 时的浮点异常(核心转储)

c++ - 参数包函数参数可以默认吗?

c++ - 为什么不能将 const 对象放入 STL 容器中?

c++ - 尝试使用外部库编译时出错