以下是最小的工作示例(好吧,实际上它是最小的非工作示例:-))。当使用 gcc(从版本 5.0 到 9.3)编译时,它会发出以下警告。它甚至似乎只在发布版本中发出警告(-02
及更高)。
Code:
class A
{
};
class B
{
const A& getA() const
{
static A a;
return a;
}
const A& get(bool b) const;
};
const A& B::get(bool b) const
{
return static_cast<const A&>(b ? getA() : getA());
}
int main(int argc, char** argv)
{
return 0;
}
编译器输出:
<source>: In member function 'const A& B::get(bool) const':
<source>:17:50: warning: function returns address of local variable [-Wreturn-local-addr]
return static_cast<const A&>(b ? getA() : getA());
<source>:17:50: note: declared here
return static_cast<const A&>(b ? getA() : getA());
Compiler returned: 0
上面的代码在 MSVC 和 clang 中都可以正常编译,甚至在 gcc 10.1 中也能正常编译。它在调试中也可以正常编译(使用-O1
or -O0
)与较旧的 gcc 版本。
您能看到代码中有什么不正确的地方吗?还是这确实是编译器问题?
观察
当我向 A 类添加删除的复制构造函数时(A(const A&) = delete;
),警告消失并且编译器停止创建局部变量。
Try你可以试穿gcc.godbolt.org https://gcc.godbolt.org/#g:!((g:!((g:!((h:codeEditor,i:(fontScale:14,j:1,lang:c%2B%2B,selection:(endColumn:3,endLineNumber:3,positionColumn:3,positionLineNumber:3,selectionStartColumn:3,selectionStartLineNumber:3,startColumn:3,startLineNumber:3),source:'class+A%0A%7B%0A%7D%3B%0A%0Aclass+B%0A%7B%0A%09const+A%26+getA()+const%0A%09%7B%0A%09%09static+A+a%3B%0A%09%09return+a%3B%0A%09%7D%0A%09const+A%26+get(bool+b)+const%3B%09%0A%7D%3B%0A%0Aconst+A%26+B::get(bool+b)+const%0A%7B%0A%09return+static_cast%3Cconst+A%26%3E(b+%3F+getA()+:+getA())%3B%0A%7D%0A%0Aint+main(int+argc,+char**+argv)%0A%7B%0A++++return+0%3B%0A%7D%0A'),l:'5',n:'0',o:'C%2B%2B+source+%231',t:'0')),k:47.14654580796961,l:'4',n:'0',o:'',s:0,t:'0'),(g:!((h:compiler,i:(compiler:g510,filters:(b:'0',binary:'1',commentOnly:'0',demangle:'0',directives:'0',execute:'1',intel:'0',libraryCode:'1',trim:'1'),fontScale:14,j:1,lang:c%2B%2B,libs:!(),options:'-O3',selection:(endColumn:12,endLineNumber:6,positionColumn:12,positionLineNumber:6,selectionStartColumn:12,selectionStartLineNumber:6,startColumn:12,startLineNumber:6),source:1),l:'5',n:'0',o:'x86-64+gcc+5.1+(Editor+%231,+Compiler+%231)+C%2B%2B',t:'0')),k:16.805462296066587,l:'4',n:'0',o:'',s:0,t:'0'),(g:!((h:output,i:(compiler:1,editor:1,fontScale:14,wrap:'1'),l:'5',n:'0',o:'%231+with+x86-64+gcc+5.1',t:'0')),k:36.04799189596379,l:'4',n:'0',o:'',s:0,t:'0')),l:'2',n:'0',o:'',t:'0')),version:4