Warning C4172: Returning a link to const std :: string is associated with a local variable. How safe is it?

I just built one of our projects at work, and I see that a new function has been added:

const std::string& ClassName::MethodName() const { return ""; } 

The compiler generates a warning:

Warning C4172: returning the address of a local variable or temporary

I think the compiler is right. How secure is this feature?

Note that the function does not return const char* , which would be OK, since string literals have a static storage duration. It returns a link to const std::string

+6
source share
4 answers

Yes, it is not safe.
The return address of a local variable or temporary dereferencing results in Undefined Behavior.

How did you comment:
Yes, the lifetime of a time reference to a permalink extends to the lifetime of a constant. But this requires the caller to call the return value in a constant reference, so the function itself will not be safe.

From the C ++ standard:
C ++ 03 12.2 Temporary objects :

The second context is when the binding is tied to a temporary one. Temporary, to which the link is attached, or temporary, which is the complete object for the subobject, with which the temporary is attached , is stored for the life of the link , except as noted below ...

The temporary binding to the reference element in the ctor-initializer constructor (12.6.2) is maintained until the constructor exits. Temporal reference to the link parameter in the function call (5.2.2) is stored until the completion of the full expression containing the call. The temporary binding to the return value in the return statement of the function (6.6.3) is maintained until the function exits

+6
source

Doing what you did actually does it inside the compiler:

 const std::string* ClassName::MethodName() const { std::string temp = ""; return &temp; } 

And returning links or pointers to local variables is bad.

+3
source

There are times when this code is safe. See GotW # 88: Candidate for "Most Important Constant . "

+2
source

This is an example that made me understand:

 #include <iostream> using std::cout; struct A{ A() { cout << "Ctor\n"; } ~A() { cout << "Dtor\n"; } }; const A& f(){ return A(); } int main(){ const A& ref = f(); cout << "1\n"; { const A& ref1 = A(); cout << "2\n"; } cout << "3\n"; } 

results

 Ctor Dtor 1 Ctor 2 Dtor 3 
+1
source

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


All Articles