Skip to content

Extend lifetime is not correct with not directly referenced temporary objects #729

Description

@nicomeunier

Code example:

#include <iostream>

struct X {
    int x;
    X() { x = 42; }
    ~X() { x = -1; }  
    const int& as_ref() const { return x; }
};

int main() {
    {
      std::cout << "x = " << X().as_ref() << std::endl;
      const int& y = X().as_ref();
      std::cout << "y = " << y << std::endl;
    }
    return 0;
}

Should print:

x = 42;
y = -1; // because X() lifetime is not extended because there is no direct reference to this temporary object

And cppinsights with options (c++20) + (show object lifetime) is giving:

/*************************************************************************************
 * NOTE: This an educational hand-rolled transformation. Things can be incorrect or  *
 * buggy.                                                                            *
 *************************************************************************************/
#include <iostream>

struct X
{
  int x;
  inline X()
  {
    this->x = 42;
  }
  
  inline ~X() noexcept
  {
    this->x = -1;
  }
  
  inline const int & as_ref() const
  {
    return this->x;
  }
  
};


int main()
{
  {
    X __temporary14_32 = X();
    std::operator<<(std::cout, "x = ").operator<<(static_cast<const X &&>(__temporary14_32).as_ref()).operator<<(std::endl);
    /* __temporary14_32.~X() */
    X __temporary15_24 = X();
    const int & y = static_cast<const X &&>(__temporary15_24).as_ref();
    std::operator<<(std::cout, "y = ").operator<<(y).operator<<(std::endl);
    /* __temporary15_24.~X() */
    /* y // lifetime ends here */
  }return 0;
}

Issue: __temporary15_24.~X() should be called just before std::operator<<(std::cout, "y = ")

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions