5

g++ 编译⚠️returning reference to local temporary object 但是运行依然得到预期结果...

 2 years ago
source link: https://www.v2ex.com/t/844896
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

V2EX  ›  C++

g++ 编译⚠️returning reference to local temporary object 但是运行依然得到预期结果?

  chuanqirenwu · 18 小时 38 分钟前 · 584 次点击

代码来自 C++ templates 第二版:

#include <cstring>
#include <iostream>

using std::cout;
using std::endl;

// maximum of two values of any type (call-by-reference)
template <typename T>
T const &max(T const &a, T const &b)
{
    cout << "T const &max(T const &a, T const &b) called" << endl;
    return b < a ? a : b;
}

// maximum of two C-strings (call-by-value)
char const *max(char const *a, char const *b)
{
    cout << "char const *max(char const *a, char const *b) called" << endl;
    cout << a << endl;
    cout << b << endl;
    return std::strcmp(b, a) < 0 ? a : b;
}

// maximum of three values of any type (call-by-reference)
template <typename T>
T const &max(T const &a, T const &b, T const &c)
{
    return max(max(a, b), c); // error if max(a,b) uses call-by-value
}

int main()
{
    char const *s1 = "frederic";
    char const *s2 = "anica";
    char const *s3 = "lucas";
    auto m2 = ::max(s1, s2, s3); // run-time ERROR
    //!!! m2 已经是一个 dangling reference ,但是仍然得到预期结果?
    cout << m2 << endl;
}

不理解的地方在最后一行,m2 已经是一个 dangling reference ,但是为什么输出仍然得到预期结果?

编译使用的是 g++:

$ g++ --version
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/4.2.1
Apple clang version 12.0.0 (clang-1200.0.31.1)
Target: x86_64-apple-darwin21.1.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin

编译输出:

$ g++ test2.cpp -o test2 -std=c++11    
test2.cpp:28:12: warning: returning reference to local temporary object [-Wreturn-stack-address]
    return max(max(a, b), c); // error if max(a,b) uses call-by-value
           ^~~~~~~~~~~~~~~~~
test2.cpp:36:17: note: in instantiation of function template specialization 'max<const char *>' requested here
    auto m2 = ::max(s1, s2, s3); // run-time ERROR
                ^
1 warning generated.

运行结果:

char const *max(char const *a, char const *b) called
frederic
anica

char const *max(char const *a, char const *b) called
frederic
lucas

lucas

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK