問題描述
在 C++ 中,當(dāng)一個(gè)應(yīng)該返回對象的函數(shù)在沒有 return 語句的情況下結(jié)束時(shí)會發(fā)生什么?返回什么?
In C++, what happens when a function that is supposed to return an object ends without a return statement? What gets returned?
例如
std::string func() {}
推薦答案
返回什么?
我們不知道.根據(jù)標(biāo)準(zhǔn),行為是未定義的.
We don't know. According to the standard, the behavior is undefined.
§6.6.3/2 返回語句[stmt.return]:
(強(qiáng)調(diào)我的)
從構(gòu)造函數(shù)、析構(gòu)函數(shù)或具有 cv void
返回類型的函數(shù)的末尾流出等價(jià)于沒有操作數(shù)的 return
.否則,從 main
(basic.start.main) 導(dǎo)致未定義行為.
Flowing off the end of a constructor, a destructor, or a function with a cv
void
return type is equivalent to areturn
with no operand. Otherwise, flowing off the end of a function other thanmain
(basic.start.main) results in undefined behavior.
事實(shí)上,大多數(shù)編譯器都會給出警告,比如 Clang:
In fact most compilers would give a warning for it, like Clang:
警告:控制到達(dá)非空函數(shù)結(jié)束[-Wreturn-type]
warning: control reaches end of non-void function [-Wreturn-type]
這篇關(guān)于當(dāng)返回對象的函數(shù)在沒有 return 語句的情況下結(jié)束時(shí)會發(fā)生什么的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!