【问题标题】:Function call destructs return object even when it isn't explicitly constructed? C++即使没有显式构造函数调用也会破坏返回对象? C++
【发布时间】:2016-10-08 09:06:00
【问题描述】:

所以我把两个 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 运行它,当它退出加法函数时,它肯定是在调用句子的析构函数。我可以提供更多代码,只是想有人可能知道没有它的问题。

【问题讨论】:

  • 你的函数被声明为返回一个Sentence,因此这个Sentence必须在某个时候被构造和销毁
  • 我重载了默认构造函数,它没有被调用,只有析构函数。当在 gdb 中逐步完成时,我从来没有遇到过构造函数@tkausl
  • Sentence Word::operator+(const Word& rightWord) const ------ 该函数在 w+w 上创建一个新词;然后销毁它,因为它没有被使用。
  • @tkausl:这不正确。是的,函数声明需要实现来构造和销毁Sentence,但它不会导致实现自动执行此操作。实现不符合要求,所以它只是未定义的行为。

标签: c++ constructor destructor


【解决方案1】:

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

事实上,您的编译器应该针对这段代码发出警告消息,甚至是错误。例如,以下使用 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() {
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-29
    • 2018-03-10
    • 2011-11-15
    • 2021-07-07
    • 1970-01-01
    • 1970-01-01
    • 2013-09-27
    相关资源
    最近更新 更多