Does Destruction of Arguments Occur Prior to Retur

2019-08-09 14:45发布

问题:

OK I have this sequence of events:

  1. I construct an r-value object
  2. I pass an iterator to that r-value object into a function as a parameter
  3. The function operates on this iterator
  4. The function returns this iterator by value
  5. I dereference the iterator

I don't know what causes cleanup of the r-value object, is it the termination of that line?

OK, now for specifics, I'm trying to come up with a better answer for this question: string Multiplication in C++ And I have the code:

const auto bar = 13U;
const char multiplicand[] = "0, ";
const auto length = strlen(multiplicand);
const string foo(&*generate_n(string(bar * length, '\0').begin(), bar * length, [&]() {
    static auto i = 0U;
    return multiplicand[i++ % length];
}) - bar * length);

So I want to know when the string that's constructed inside generate_n should be destroyed. Incidentally this seems to work fine on gcc 5.1: http://ideone.com/Y8rDs5 But I could just be getting undefined behavior. This is implied by the fact that the code segfaults on Visual Studio 2015.

回答1:

Temporaries such as string(bar * length, '\0') are destroyed at the end of the full expression. The full expression is the initializer of const string foo. Hence, the temporary string will not be destroyed before the ctor of foo returns.