【问题标题】:Why does'nt the compiler throw error for not returning this pointer for a function whose return type is classname&为什么编译器不为返回类型为类名的函数返回此指针而引发错误&
【发布时间】:2016-04-11 11:11:02
【问题描述】:

为什么编译器不为返回类型为类名的函数返回此指针而抛出错误&

例如:在 readonly 、 readwrite 等函数中,即使我们注释 return *this 并且不返回任何东西,这似乎工作正常,并且链接机制在 main 函数中也完美工作。

这些函数会自动返回 *this 吗?

class OpenFile {
public:
  OpenFile(const std::string& filename);

  OpenFile& readonly();  // changes readonly_ to true
  OpenFile& readwrite(); // changes readonly_ to false
  OpenFile& createIfNotExist();
  OpenFile& blockSize(unsigned nbytes);

private:
  friend class File;
  std::string filename_;
  bool readonly_;          // defaults to false [for example]
  bool createIfNotExist_;  // defaults to false [for example]

  unsigned blockSize_;     // defaults to 4096 [for example]

};
inline OpenFile::OpenFile(const std::string& filename)
  : filename_         (filename)
  , readonly_         (false)
  , createIfNotExist_ (false)
  , blockSize_        (4096u)
{ }
inline OpenFile& OpenFile::readonly()
{ readonly_ = true; return *this; }
inline OpenFile& OpenFile::readwrite()
{ readonly_ = false; return *this; }
inline OpenFile& OpenFile::createIfNotExist()
{ createIfNotExist_ = true; return *this; }
inline OpenFile& OpenFile::blockSize(unsigned nbytes)
{ blockSize_ = nbytes; return *this; }

main()
{
//OpenFile *obj = new OpenFile();
  OpenFile f = OpenFile("foo.txt")
       .readonly()
       .createIfNotExist()
       .blockSize(1024);
}

删除return语句根本不会影响代码,像这样

inline OpenFile& OpenFile::readonly()
{ readonly_ = true;  }
inline OpenFile& OpenFile::readwrite()
{ readonly_ = false;  }
inline OpenFile& OpenFile::createIfNotExist()
{ createIfNotExist_ = true; }
inline OpenFile& OpenFile::blockSize(unsigned nbytes)
{ blockSize_ = nbytes;  }

编译器如何处理这些函数,还是通过查看返回类型自动返回 *this?

【问题讨论】:

  • 你应该得到类似“在非无效函数上缺少返回语句”的东西。您可以添加一些警告并将警告视为错误来解决此问题。
  • 编译器至少应该发出一个警告,如果你愿意,你可以把它变成一个错误:stackoverflow.com/a/3487031/996886

标签: c++ c++11 c++14 chaining constructor-chaining


【解决方案1】:

编译器是如何处理这些函数的

以一种未定义的方式

还是通过查看返回类型自动返回 *this?

没有。程序的行为是不可预测的,当然也不会是正确的。

但它似乎工作

很可能在未优化的版本中。持有this 指针的寄存器可能没有被修改。

等到优化器开始在您的发布版本中内联您的代码。欣赏烟花。

为什么编译器不抱怨?

如果您启用警告,它会。您应该始终启用所有警告。它们可以帮助您避免错误的代码:

/tmp/gcc-explorer-compiler116311-75-17mquww/example.cpp: In member function 'OpenFile& OpenFile::readonly()':
28 : warning: no return statement in function returning non-void [-Wreturn-type]
{ readonly_ = true; }
^
Compiled ok

从 §6.6.3 (2):

从函数的末尾流出相当于没有值的返回;这导致 值返回函数中未定义的行为。

【讨论】:

  • 它们可以帮助您避免不正确的代码嗯...它们可以帮助您避免明显不正确的代码。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-11
  • 1970-01-01
  • 1970-01-01
  • 2022-01-14
相关资源
最近更新 更多