为什么允许赋值运算符返回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;
}
问题:
- 为什么这是合法的? (为什么要编译)
- 为什么有效?
我在很多地方读到“赋值运算符应该返回 *this 这样你就可以进行赋值链接”,这完全有道理,但为什么上面的方法有效?
最佳答案
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 themain
function (destroying any objects with automatic storage duration) and callingstd::exit
with the return value as the argument. If control reaches the end ofmain
without encountering a return statement, the effect is that of executingreturn 0;
最后:
Why does it work?
未定义的行为意味着你的程序可能在某些机器上运行但在其他机器上不能运行;或者它今天可以在所有机器上运行,但明天就不行;或者它会导致你的程序有一些奇怪的、不可预知的结果;包括(这是最坏的情况)似乎运行良好。
关于c++ - 没有 return 语句的重载赋值运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15474512/