vector and const

后端 未结 10 1718
無奈伤痛
無奈伤痛 2020-12-03 07:13

Consider this

 void f(vector& p)
 {
 }
 int main()
 { 
  vector nonConstVec;
  f(nonConstVec);
 }

The followi

10条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-03 07:54

    I've added a few lines to your code. That's sufficient to make it clear why this is disallowed:

    void f(vector& p)
     {
        static const T ct;
        p.push_back(&ct); // adds a const T* to nonConstVec !
     }
     int main()
     { 
      vector nonConstVec;
      f(nonConstVec);
      nonConstVec.back()->nonConstFunction();
     }
    

提交回复
热议问题