c++ - 没有 return 语句的重载赋值运算符

标签 c++ assignment-operator

为什么允许赋值运算符返回void?为什么赋值链在这种情况下有效?看看代码,就会很清楚我在说什么。

代码:

struct Foo
{
   std::string str;

   Foo(const std::string& _str)
   : str(_str)
   {
   }

   Foo& operator=(const Foo& _foo)
   {    
      str = _foo.str;
      //return *this; /* NO RETURN! */
   }
};

int main()
{
   Foo f1("1");
   Foo f2("2");
   Foo f3("3");
   f1 = f2 = f3 = Foo("4");

   std::cout << "f1: " << f1.str << std::endl;
   std::cout << "f2: " << f2.str << std::endl;
   std::cout << "f3: " << f3.str << std::endl;

   return 0;
}

问题:

  1. 为什么这是合法的? (为什么要编译)
  2. 为什么有效?

我在很多地方读到“赋值运算符应该返回 *this 这样你就可以进行赋值链接”,这完全有道理,但为什么上面的方法有效?

尝试一下:
online c++ workspace with the code from above

最佳答案

Why is this legal? (why does it compile at all)

这是合法的,并且会在您的程序中注入(inject)未定义的行为。您的编译器至少应该警告您(如果您设置足够高的警告级别,我相信它会警告您)。

根据 C++11 标准的第 6.6.3/2 段:

Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavior in a value-returning function.

唯一的异常(exception)是 main() 函数,它允许缺少 return 语句。根据第 3.6.1/5 段:

A return statement in main has the effect of leaving the main function (destroying any objects with automatic storage duration) and calling std::exit with the return value as the argument. If control reaches the end of main without encountering a return statement, the effect is that of executing

return 0;

最后:

Why does it work?

未定义的行为意味着你的程序可能在某些机器上运行但在其他机器上不能运行;或者它今天可以在所有机器上运行,但明天就不行;或者它会导致你的程序有一些奇怪的、不可预知的结果;包括(这是最坏的情况)似乎运行良好。

关于c++ - 没有 return 语句的重载赋值运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15474512/

相关文章:

c++ - 通过赋值初始化类对象

c++ - 通过引用传递值

c++ - 即使编译失败,我是否需要删除 OpenGL 着色器对象?

python - 为什么 x -= x + 4 返回 -4 而不是 4

c - 何时在 c 中计算表达式中括号内的赋值运算符?

c++ - 复制控制函数中如何处理 C++ 数组成员?

c++ - c++中私有(private)复制构造函数有什么用

c++ - Visual Studio 2012 应用程序窗口创建/调整大小不同于 VS2008 窗口创建?为什么?

c++ - 如何在 `QQmlApplicationEngine` 派生类中访问 `QQuickItem` 的对象?

c++ - 将虚函数添加到子类而不在子类中?