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);
}
In the line myVec= a.getVec(), there is a copy of vector although it is returned by reference. If flag is not true, an empty vector will be passed.
Anyway to avoid this copy ?
func1(flag ? a.getVec() : std::vector<int>());
is one way.
This will work if func1 takes the vector by const reference, since both anonymous temporaries can bind to it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With