const_cast and std::move to remove constness from non-reference

隐身守侯 提交于 2019-12-04 22:30:51

Technically speaking, you are exposing your program to undefined behavior. Since original object C (a temporary) was declared const, const-casting and modifying it is illegal and against the standard. (I assume, move constructor does some modifications to the movee).

That being said, it probably works in your environment and I do not see a better workaround.

Casting away the const will lead to undefined behavior if the move constructor for bar modifies anything. You can probably work around your issue like this without introducing undefined behavior:

struct wrapped_bar {
    mutable bar wrapped;
};

bar buz()
{
    return foo<wrapped_bar>().wrapped;
}

Having the wrapped member be mutable means that the member is non-const even though the wrapped_bar object as a whole is const. Based on how foo() works, you may need to add members to wrapped_bar to make it work more like a bar.

As result of function call is by definition an R-Value itself, you do not need to apply std::move on it in return statement - const_cast<bar&&>(foo<bar>()) should be enough. That make code a little bit simpler to read.

Still - there is no standard guarantee that this will always work for all bar types. Even more - this might in some cases lead to undefined behavior.(Imagine some very intrusive optimization, which completely eradicates foo and makes its result an object in "static data" segment of memory - like if foo was a constexpr. Then calling moving constructor, which probably modifies its argument, might lead to access violation exception).

All you can do is either switch to different library (or, if possible, ask library maintainer to fix API) or create some unit test and include it in your build process - as long as test passes, you should be OK (remember to use same optimization settings as in "production" build - const_cast is one of those things which strongly depends on compilation settings).

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