C ++ returns a link to temporary files or stores them in objects

Consider the following code related to const links:

const int & func (const int &x)
{
    return x;
}

struct Foo {
    Foo (const int &x)
    : m_x(x) {}

    const int & getX ()
    { return m_x; }

    const int &m_x;
};

I would like to know that, if any, is now allowed:

int x = func(int(7));
int y = Foo(int(7)).getX();

Is there any guarantee that the temporary object intstill exists before it is used by the destination or getX?

UPDATE : So it seems that it is safe, but why exactly?

  • Is this because temporary links are recursively linked to constant links and are guaranteed to exist as long as there are linked links to them?
  • Or is it because they are guaranteed to exist for the duration of full expression?

Consider the case of an edge that stores a pointer instead of a link:

struct Foo {
    Foo (const int &x)
    : m_x(&x) {}

    const int & getX ()
    { return *m_x; }

    const int *m_x;
};

int y = Foo(int(7)).getX();

, 1) , . 2) , .

+5
2

, x y. .

12.2

4) , , . . , , , .

5) . , , , , , . ctor- (12.6.2) . (5.2.2) , . return (6.6.3) . , , , , , , . , , , . , , , (3.7.1, 3.7.2); , obj1 - , ; obj2 - , obj2. [ :

class C 
{ 
/ / ... 
public : 
    C(); 
    C(int ); 
    friend C operator +(const C&, const C&); 
    ~C(); 
}; 
C obj1 ; 
const C& cr = C (16)+ C (23); 
C obj2 ; 

C (16) + C (23) . T1 C (16), T2 C (23), T3 - . 3 . T1 T2. , T1 T2, , T2 T1. T1 T2 +; , +. T3, cr crs, . , , T3 . , obj1 T3 T3 obj2, , obj2 T3 T3 obj1. -end ]

+7

. const, , , . , .

const:

void foo(const someclass& bla = someclass()); // bind const ref with default constructed someclass
+1

All Articles