Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
461 views
in Technique[技术] by (71.8m points)

c++ - What happens when a function that returns an object ends without a return statement

In C++, what happens when a function that is supposed to return an object ends without a return statement? What gets returned?

e.g.

std::string func() {}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

What gets returned?

We don't know. According to the standard, the behavior is undefined.

§6.6.3/2 The return statement [stmt.return]:

(emphasis mine)

Flowing off the end of a constructor, a destructor, or a function with a cv void return type is equivalent to a return with no operand. Otherwise, flowing off the end of a function other than main (basic.start.main) results in undefined behavior.

In fact most compilers would give a warning for it, like Clang:

warning: control reaches end of non-void function [-Wreturn-type]


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...