Default move constructor vs. Default copy constructor vs. Default assignment operator

后端 未结 3 506
-上瘾入骨i
-上瘾入骨i 2021-02-11 16:30

Why does C++ compiler have more restriction on automatically generated move constructors than on automatically generated copy constructor or assignment operator ?

Automa

3条回答
  •  悲&欢浪女
    2021-02-11 17:01

    As far as I know, this is because of downward compatibility. Consider classes written in C++ (before C++11) and what would happen if C++11 would start to automatically generate move-ctors in parallel to existing copy-ctors or generally any other ctor. It would easily break existing code, by-passing the copy-ctor the author of that class wrote. Hence, the rules for generating a move-ctor where crafted to only apply to "safe" cases.

    Here's the article from Dave Abrahams about why implicit move must go, which eventually led to the current rules of C++11.

    And this is an example how it would fail:

    // NOTE: This example assumes an implicitly generated move-ctor
    
    class X
    {
    private:    
        std::vector v;
    
    public:
        // invariant: v.size() == 5
        X() : v(5) {}
    
        ~X()
        {
            std::cout << v[0] << std::endl;
        }
    };
    
    int main()
    {
        std::vector y;
    
        // and here is where it would fail:
        // X() is an rvalue: copied in C++03, moved in C++0x
        // the classes' invariant breaks and the dtor will illegally access v[0].
        y.push_back(X());
    }
    

提交回复
热议问题