Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

gcc

clang

c++14

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?

like image 882
Dev Null Avatar asked Oct 06 '17 06:10

Dev Null


1 Answers

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.

like image 81
Praetorian Avatar answered Sep 28 '22 13:09

Praetorian