简体   繁体   中英

What happens in C++ if you pass an anonymous object into a function that takes a 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.

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.

In C++ you can't pass a temporary object to a function that takes a non-constant reference. The example you posted above will not compile. If your compiler compiles it, it is a quirk (extension) of your compiler. If your compiler compiles it without even issuing a diagnostic message, your compiler is broken.

A temporary object (result of your makeRandomData() call), can only be passed to mean through a const-qualified reference. Ie your mean has to be declared as

int mean(const vector<int> & data) 

in which case the reference will be bound either directly to the temporary object returned by makeRandomData() , or to another copy of that temporary object the compiler might choose to create. (The latter is unlikely in this case, but might happen in theory.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM