Danger with virtual base move assignment operators when they are now allowed to be used?

不问归期 提交于 2019-12-21 18:06:20

问题


This concerns the resolution of C++ Issue http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1402 . Summary:

template<typename T>
struct wrap
{
   wrap() = default;

   wrap(wrap&&) = default;
   wrap(const wrap&) = default;

   T t;
};

struct S {
   S(){}
   S(const S&){}
   S(S&&){}
};

typedef wrap<const S> W;

// Error, defaulted move constructor of "wrap<const S>" is deleted!
W get() { return W(); }

(The issue is that we are getting an error for this snippet, even though the compiler could simply use the copy constructor of "S", as it does when the user explicitly writes the move constructor of "wrap". The issue was resolved to ignore deleted move constructors (and assignment operators) during overload resolutions, hence using the copy constructor above as desired.)

When the resolution was drafted, the following comment was made about this resolution:

There are no additional restrictions for implicit/defaulted move operations relative to copy. This means that move assignment in a virtual base is dangerous (and compilers should probably warn) [...] But we decided in Batavia that we weren't going to preserve all C++03 code against implicit move operations, and I think this resolution provides significant performance benefits.

Can someone please describe what the concern with virtual base move assignment operators is?


回答1:


Consider:

#include <iostream>

struct A
{
    A() = default;
    A(const A&) = default;
    A(A&&) = default;
    A& operator=(const A&) {std::cout << "operator=(const A&)\n"; return *this;}
    A& operator=(A&&) {std::cout << "operator=(A&&)\n"; return *this;}
};

struct B
    : virtual public A
{
};

struct C
    : virtual public A
{
};

struct D
    : public B,
      public C
{
};

int
main()
{
    D d1, d2;
    d1 = std::move(d2);
}

I believe this program should output:

operator=(A&&)
operator=(A&&)

For me it actually outputs:

operator=(const A&)
operator=(const A&)

But I think this is just a clang bug (compiled with -std=c++1y). If I am correct about what the output should be, then the danger is that the move assignment operator is called twice. This is harmless (though potentially expensive) with the copy assignment operator, but not with the move assignment operator.



来源:https://stackoverflow.com/questions/17252869/danger-with-virtual-base-move-assignment-operators-when-they-are-now-allowed-to

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