Does the const link contain a lifetime extension for the temporary object returned by the temporary object?

I know that a constant reference extends the life of a temporary locally. Now I ask myself whether it is possible to expand this attractiveness along the chain of temporary objects, that is, if I can confidently determine:

std::string const& foo = aBar.getTemporaryObject1().getTemporaryObject2();

I feel that since the first method aBar.getTemporaryObject1()returns a temporary object, aBar.getTemporaryObject2()this property is not executed.

0
source share
3 answers

Life extension only applies when the link is directly related to that temporary one.

, .

:

std::string const& foo = aBar.getTemporaryObject1().getTemporaryObject2();

foo getTemporaryObject2(), , , . , - . , .

, getTemporaryObject1(), , ( getTemporaryObject2 return - , , -, std::string ).

+4
std::string const& foo = aBar.getTemporaryObject1().getTemporaryObject2();

(TemporaryObject2 , TemporaryObject1)

std::string const& foo = aBar.getTemporaryObject1().member;

(TemporaryObject1).

std::string const& foo = aBar.getTemporaryObject1().getReference();

: TemporaryObject1 .

+3

. , , ( ).

string & foo1()
{
  string tmp("hello");
  return tmp; 
}

string foo2()
{
  string tmp("hello");
  return tmp; 
}

void foo3()
{
  const string & r1 = foo1(); // crashes later.
  const string & r2 = foo2(); // Ok, object lives in scope of foo3.
}

- , :

const string & r2 = string("hello");

, . .

0

All Articles