Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens in C++ if you pass an anonymous object into a function that takes a reference?

Tags:

c++

reference

IE what happens if you have this following piece of code?

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());
}

Am I correct in thinking that C++ will just preserve the newly created object for the life of mean, and then destroy it afterwards since it goes out of scope?

Also, how does this work/interfere with RVO?

Thanks in advance.

EDITED: Added const, forgot to put that in.

like image 828
Xzhsh Avatar asked Dec 01 '22 10:12

Xzhsh


1 Answers

My psychic powers tell me that you're compiling this on Visual C++, which is why it even works. In standard C++, you cannot pass an rvalue (which is what the return value of makeRandomData is) to a reference-to-non-const, so the question is moot.

However, the question is still valid if you change the signature of mean to take a const vector<int>&. In which case it all boils down to the lifetime of the temporary - which is defined to last until the end of the "full expression" in which it occurs. In your particular case, the full expression is the entire initializer of results. In case of an expression statement, the full expression is that entire statement.

The Standard does not specify any way in which function arguments can inhibit RVO, but, of course, RVO is a mandate to the compiler to do a particular optimization regardless of visible side effects, not a requirement to do it. When (and if) RVO happens is entirely up to the specific compiler you're using. That said, there does not seem to be any reason why it should be affected by this in any way.

like image 116
Pavel Minaev Avatar answered Dec 10 '22 04:12

Pavel Minaev