Question about the exact time of destruction of temporary objects in C ++

is safe code (it works in DEBUG):

void takesPointer(const Type* v);//this function does read from v, it doesn't alter v in any way
Type getValue();
...
takesPointer(&getValue());//gives warning while compiling "not an lvalue"
...
Type tmp = getValue();
takesPointer(&tmp);//this is safe, and maybe I should just do it, instead of posting here

so - is it safe? should i just forget about it and use code with explicit tmp?

but anyway - I still wonder if the optimizer is allowed to kill the temporary before returning from this call:

takePointer(&getValue())

EDIT: Thank you all! unfortunately, I cannot change the "takePointer" function (this is part of the library), I could only wrap it in the "takeReference" function, which calls takePointer - this will eliminate the copy, or the compiler is still allowed to create a copy ("Type" - it is an int-3x3-Matrix, so that would not be so, but still ...)?

inline void takesReference(const Type& v){ takesPointer(&v); }

On the time of destruction: will it be destroyed after the "takePointer" RETURNS or after its call?

+3
5

, . ,

void takesPointer(const Type* v);

void takesPointer(const Type& v);

:

takesPointer(getValue());

const, .

+10

&getValue() - , lvalue. , , , , . " " , ,

// the temporary string is alive until the whole expression has been processed
cout << string("hello");

- . , , . , , , . , , , .

+7

* .

const Type& tmp = getValue(); 
takesPointer(&tmp);

, . , :

#include "iostream"
class Type
{
public:
    explicit Type(int val) : m_val(val) { std::cout << "ctor";};
    Type(const Type& copy)
    {
        std::cout << "copy";
    };
private:
    int m_val;
};

Type getValue() { Type r(0); return r;};
void takesPointer(const Type* const)
{

};

int main(int argc, char* argv[])
{
    const Type tmp = getValue(); 
    takesPointer(&tmp);
}

"ctor" "ctorcopy" . (MVS2005)

+1

-const- lvalue, lvalue.

, getValue() takePointer().

0

, , . , const-reference

takesPointer( &(const Type &) getValue() );

, , .

, ( , ). , .

, "" , , , ""

Type *p;
p = &(Type &) (const Type &) getValue(), modify(p), print(p), modifyAgain(p), print(p);
// Not using C++ casts for brevity

, .

0

Source: https://habr.com/ru/post/1734412/


All Articles