即使未显式构造,函数调用也会破坏 return 对象? C++

Function call destructs return object even when it isn't explicitly constructed? C++

所以我调用了两个 Word 对象的重载加法

Word w;
w+w;

声明和定义为:

Sentence operator+(const Word&) const;

Sentence Word::operator+(const Word& rightWord) const{
std::cout<<"Entering function Word::operator+(const Word&)."<<std::endl;
std::cout<<"Leaving function Word::operator+(const Word&).\n"<<std::endl;
}

执行 w+w 后,一个 Sentence 对象被解构(我重载了析构函数以打印到 stdout)我之前创建了一个 sentence 对象,但我认为这不会影响它。我不明白一个句子对象在甚至没有构造时是如何被解构的(也重载了默认构造函数)。我也不明白为什么会创建它,因为我什至没有真正归还它。我通过 gdb 运行 它退出加法函数时肯定会调用句子的析构函数。我可以提供更多代码,只是想如果没有它,有人可能知道问题所在。

如果非void 函数没有返回任何内容,则为未定义行为。您观察到的所有效果都不是由 C++ 语言定义的,是特定于您的编译器的 and/or 只是随机的。

事实上,您的编译器应该对这段代码发出警告信息,甚至是错误。例如,以下代码使用 Visual C++ 2015 生成 error C4716: 'Word::operator+': must return a value

#include <iostream>

struct Sentence {};

struct Word {
Sentence operator+(const Word&) const;
};

Sentence Word::operator+(const Word& rightWord) const{
std::cout<<"Entering function Word::operator+(const Word&)."<<std::endl;
std::cout<<"Leaving function Word::operator+(const Word&).\n"<<std::endl;
} // error C4716

int main() {
}