Validity of casting a Base pointer to a Derived pointer when Derived only adds methods

不打扰是莪最后的温柔 提交于 2019-12-14 02:17:43

问题


First, the question is very similar to downcasting shared pointer to derived class with additional functionality is, where there are good answers. But I'd like to have explanation on why this is valid (or not) and when not using shared pointers. So :

class Base { /* ... */ };

class Derived : public Base
{
public:
    void additionnalFunc(int i){ /* access Base members */ }
};

int main(){
Base b;
Derived* d = (Derived*) &b; // or static_cast ?
d->additionnalFunc(3); // works ok.
}

This works as expected with gcc. So my question is it safe/valid ? with any compiler or architecture ? if not, why ?

To explain why this question, here is the context.

  • I have "Base" objects.
  • I can't modify the Base class
  • I have a set of templated functions which requires the same interface as Base, except a few additional functions.
  • I want to be able to use this templated library with my Base objects
  • Because of the additional functions, the above is impossible. But these functions are trivial to implement from Base.
  • Also I want to be as efficient as possible (avoid conversions and indirections)

So if the above trick is valid, it could be a good solution... But maybe there is a better design to solve this issue ?


回答1:


This is undefined behaviour. Whether it "works" or not on any given compiler is probably besides the point; you cannot rely on this working in general.*

In the scenario you've described, it sounds like the best solution is just to create some free functions that take a Base as an argument. Of course, if the required functionality relies on protected members, then you have a problem! (And I'm not sure there's a good solution, other than to find a way to avoid needing such access.)


* And that's true even if you never change your compiler. The compiler is free to assume that all code is "correct", so a slight change to your code may trigger an optimization that renders the above trick useless.

(Of course, I'm not going to to suggest that this will definitely happen, merely that it could.)



来源:https://stackoverflow.com/questions/15328297/validity-of-casting-a-base-pointer-to-a-derived-pointer-when-derived-only-adds-m

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