Why does gcc warn about calling a non-trivial move assignment operator with std::tuple and virtual inheritance?

徘徊边缘 提交于 2020-12-23 03:29:48

问题


In the following example gcc 7 gives a warning:

defaulted move assignment for 'B' calls a non-trivial move assignment operator for virtual base 'A' [-Wvirtual-move-assign]

if I create an std::tuple<B> object. Clang 5 doesn't report any problems. Also the problem goes away if vector is removed from Base. Example.

#include <tuple>
#include <vector>

class Base
{
public:
    virtual ~Base();
    std::vector<int> v;
};

class A : public Base
{
};

class B : public virtual A
{
};

int main()
{
    B *b = new B;
    B another{*b}; // <<<--- this compiles
    std::tuple<B> t; // <<<--- gives warning
}

Why does it happen in presence of std::tuple (and absence of move assignment) and what is the proper way to fix it if I need to keep such a hierarchy?


回答1:


The warning is unrelated to tuple, it is triggered by a move assignment of B. For instance, the following code generates the warning

B b;
B t;
t = std::move(b);

The gcc documentation explains the intent of the warning

-Wno-virtual-move-assign

Suppress warnings about inheriting from a virtual base with a non-trivial C++11 move assignment operator. This is dangerous because if the virtual base is reachable along more than one path, it is moved multiple times, which can mean both objects end up in the moved-from state. If the move assignment operator is written to avoid moving from a moved-from object, this warning can be disabled.

Here's an example that demonstrates the problem

struct Base
{
    Base() = default;
    Base& operator=(Base&&)
    {
        std::cout << __PRETTY_FUNCTION__ << '\n';
        return *this; 
    }
};

struct A : virtual Base {};

struct B : virtual Base {};

struct C : A, B {};

int main()
{
    C c;
    c = C();
}

This produces the output

Base& Base::operator=(Base&&)
Base& Base::operator=(Base&&)

showing that the single Base instance was moved assigned to twice, once by each move assignment operator of A and B. The second move assignment is from an already moved from object, which could cause the contents from the first move assignment to be overwritten.

Note that clang also generates a warning in my example, it's probably detecting that A is not reachable via two paths in your example and not emitting the warning.

The way to fix it is to implement move assignment operators for A and B that can detect that Base has been moved from and omit a second move assignment.



来源:https://stackoverflow.com/questions/46599222/why-does-gcc-warn-about-calling-a-non-trivial-move-assignment-operator-with-std

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!