繁体   English   中英

即使未明确构造函数调用,它也会破坏返回对象? 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)我之前创建了一个句子对象,但是我不认为这会影响它。 我什至不理解甚至没有构造一个句子对象时也如何对其进行解构(也超载了默认构造函数)。 我也不明白为什么会创建它,因为我什至没有真正返回它。 我通过gdb运行它,当它退出加法函数时,它肯定是在调用句子的析构函数。 我可以提供更多代码,只是想知道如果没有它,有人可能会知道问题。

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

实际上,您的编译器应该为这段代码发出警告消息,甚至发出错误消息。 例如,以下产生error C4716: 'Word::operator+': must return a value使用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() {
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM