How to generate a compiler warning/error when object sliced

后端 未结 8 1571
执笔经年
执笔经年 2021-02-04 03:58

I want to know if it is possible to let compiler issue a warning/error for code as following:

Note:

1. Yea, it is bad programming style and

8条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-04 04:04

    I would suggest adding a constructor to your base class which takes a const reference to the derived class explicitly (with a forward declaration). In my simple test app, this constructor gets called in the slicing case. You could then at least get a run-time assertion, and you could probably get a compile-time assertion with clever use of templates (eg: instantiate a template in a way which generates a compile-time assertion in that constructor). There may also be compiler-specific ways to get compile time warnings or errors when you call explicit functions; for example, you can use "__declspec(deprecated)" for the "slice constructor" in Visual Studio to get a compile-time warning, at least in the function-call case.

    So in your example, the code would look like this (for Visual Studio):

    class Base { ...
        __declspec(deprecated) Base( const Derived& oOther )
        {
            // Static assert here if possible...
        }
    ...
    

    This works in my test (compile-time warning). Note that it doesn't solve the copy case, but a similarly-constructed assignment operator should do the trick there.

    Hope this helps. :)

提交回复
热议问题