mercredi 3 novembre 2021

Passing actual argument by function return value only has one copy temporary variable or two?

I know when passing argument by value, compiler calls copy constructor, creates a temporary variable to store the copy value and uses it in function.

But I want to know if passing anonymous function return value will the compiler creates two temporary variables? For example,

void func(Foo foo){..}

func(make_foo(args));

First the compiler creates a variable to store result of make_foo(args), then it creates second variable, which is copy of first, to formal parameter of func()?

I did a small test by make_shared, from the result it seems only one temporary variable was created. But I don'y know whether the first variable has been released, like leaving its scope?

This is my test code:

void test(std::shared_ptr<int> sp) {
  std::cout << sp.use_count() << std::endl;
  return;
}

int main(int argc, char const* argv[]) {
  auto sp = std::make_shared<int>(10);
  auto sp2 = std::shared_ptr<int>(sp);
  std::cout << sp.use_count() << std::endl;
  test(std::shared_ptr<int>(sp));
  std::cout << sp.use_count() << std::endl;
}

result is

2
3
2

Aucun commentaire:

Enregistrer un commentaire