Why does operator ++ return a non-const value?

后端 未结 3 680
不思量自难忘°
不思量自难忘° 2020-12-30 23:17

I have read Effective C++ 3rd Edition written by Scott Meyers.

Item 3 of the book, \"Use const whenever possible\", says if we want to prevent rvalues f

3条回答
  •  失恋的感觉
    2020-12-30 23:56

    I'm pretty sure that this is because it would play havoc with rvalue references and any sort of decltype. Even though these features were not in C++03, they have been known to be coming.

    More importantly, I don't believe that any Standard function returns const rvalues, it's probably something that wasn't considered until after the Standard was published. In addition, const rvalues are generally not considered to be the Right Thing To Do™. Not all uses of non-const member functions are invalid, and returning const rvalues is blanketly preventing them.

    For example,

    auto it = ++vec.begin();
    

    is perfectly valid, and indeed, valid semantics, if not exactly desirable. Consider my class that offers method chains.

    class ILikeMethodChains {
    public:
        int i;
        ILikeMethodChains& SetSomeInt(int param) {
            i = param;
            return *this;
        }
    };
    ILikeMethodChains func() { ... }
    ILikeMethodChains var = func().SetSomeInt(1);
    

    Should that be disallowed just because maybe, sometimes, we might call a function that doesn't make sense? No, of course not. Or how about "swaptimization"?

    std::string func() { return "Hello World!"; }
    std::string s;
    func().swap(s);
    

    This would be illegal if func() produced a const expression - but it's perfectly valid and indeed, assuming that std::string's implementation does not allocate any memory in the default constructor, both fast and legible/readable.

    What you should realize is that the C++03 rvalue/lvalue rules frankly just don't make sense. They are, effectively, only part-baked, and the minimum required to disallow some blatant wrongs whilst allowing some possible rights. The C++0x rvalue rules are much saner and much more complete.

提交回复
热议问题