-1

Assuming MyClass has an implicit constructor that takes an int as an argument, why is there a difference between MyClass being explicitly constructed vs. implicitly done so in terms of when the temporary gets destroyed? In one case it results in a dangling reference while in another it does not.

template <typename T>
void f(const T &x) {
   cout << __PRETTY_FUNCTION__ << endl;
}

int main()
{
   f(std::tuple<const MyClass &>(10));
   cout << "---------------\n";
   f(std::tuple<const MyClass &>(MyClass{}));
}

Output:

MyClass::MyClass(int)
MyClass::~MyClass()
void f(const T&) [with T = std::tuple<const MyClass&>]
---------------
MyClass::MyClass()
void f(const T&) [with T = std::tuple<const MyClass&>]
MyClass::~MyClass()
user3882729
  • 1,339
  • 8
  • 11

1 Answers1

1

std::tuple has a templated constructor taking arbitrary types (overload (3) here). So, in the first case int is passed to tuple constructor, a temporary MyClass is constructed there, then destroyed when that constructor returns and before f is called.

In the second case, the MyClass temporary is constructed in main, and survives past the f call.

Igor Tandetnik
  • 50,461
  • 4
  • 56
  • 85