What happens in C ++ if you pass an anonymous object to a function using a link?

IE, what happens if you have the following code snippet?

int mean(const vector<int> & data) {
  int res = 0;
  for(size_t i = 0; i< data.size(); i++) {
    res += data[i];
  }
  return res/data.size();
}

vector<int> makeRandomData() {
  vector<int> stuff;
  int numInts = rand()%100;
  for(int i = 0; i< numInts; i++) {
    stuff.push_back(rand()%100);
  }
}

void someRandomFunction() {
  int results = mean(makeRandomData());
}

Do I correctly believe that C ++ will simply save the newly created object for the life of the average, and then destroy it after it goes beyond?

Also, how does it work / interfere with RVO?

Thanks in advance.

EDITED: constant added, forgot to insert it.

+3
source share
2 answers

My psychic powers tell me that you are compiling this in Visual C ++, so it even works. In standard C ++, you cannot pass rvalue (which is the return value makeRandomData) to a non-const reference, so the question is debatable.

, mean, const vector<int>&. , , " ", . - results. - .

, RVO, , , RVO - , . ( ) RVO , . , -, , .

+15

++ , . . , quirk () . , , .

( makeRandomData()) mean . mean

int mean(const vector<int> & data) 

, makeRandomData(), , . ( , .)

+4

Source: https://habr.com/ru/post/1762756/


All Articles