Objects of immovable classes are not subject to change?

When compiling with Clang 3.9.1 or GCC 6.3.0, throwing movable but not copyable objects seems to work fine:

struct MovableNonCopyable {
    MovableNonCopyable();
    ~MovableNonCopyable();
    MovableNonCopyable(MovableNonCopyable &&);
    MovableNonCopyable(MovableNonCopyable const &) = delete;
    MovableNonCopyable & operator=(MovableNonCopyable &&);
    MovableNonCopyable & operator=(MovableNonCopyable const &) = delete;
};

void f() { throw MovableNonCopyable(); }

But throwing copied, but not movable objects, such as:

struct CopyableNonMovable {
    CopyableNonMovable();
    ~CopyableNonMovable();
    CopyableNonMovable(CopyableNonMovable &&) = delete;
    CopyableNonMovable(CopyableNonMovable const &);
    CopyableNonMovable & operator=(CopyableNonMovable &&) = delete;
    CopyableNonMovable & operator=(CopyableNonMovable const &);
};

void g() { throw CopyableNonMovable(); }

instead, causes a compilation error, for example:

test.cpp: In function 'void g()':
test.cpp:21:41: error: use of deleted function 'CopyableNonMovable::CopyableNonMovable(CopyableNonMovable&&)'
    void g() { throw CopyableNonMovable(); }
                                        ^
test.cpp:15:9: note: declared here
        CopyableNonMovable(CopyableNonMovable &&) = delete;
        ^~~~~~~~~~~~~~~~~~

Why is this? According to [except.throw # 5] , it should be the other way around, i.e. Copy constructor should be available.

+4
source share
1 answer

Here you explicitly ask the compiler to prevent the construction of rvalue objects.

CopyableNonMovable(), "", . , , - , rvalues ​​ rvalue. , .

, , . r const CopyableNonMoveable

+2

Source: https://habr.com/ru/post/1668279/


All Articles