Safe to return a vector populated with local variables?

后端 未结 1 631
甜味超标
甜味超标 2021-02-08 10:34

Is it safe to return a vector that\'s been filled with local variables?

For example, if I have...

#include 

struct Target
{
public:
             


        
1条回答
  •  深忆病人
    2021-02-08 11:10

    Elements get copied when you push_back them into a vector (or assign to elements). Your code is therefore safe – the elements in the vector are no references to local variables, they are owned by the vector.

    Furthermore, you don’t even need to return a pointer (and never handle raw pointers, use smart pointers instead). Just return a copy instead; the compiler is smart enough to optimise this so that no actual redundant copy is made.

    0 讨论(0)
提交回复
热议问题