const_cast和std :: move从非引用中删除const [英] const_cast and std::move to remove constness from non-reference

查看:205
本文介绍了const_cast和std :: move从非引用中删除const的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个外部库,我不能修改。库声明一个模板函数,由于某种原因返回 const 非引用对象:

  template< class C> 
const C foo();

我有另一个外部库,我也不能修改。该库声明一个不可复制的类,并且只有一个非const对象的移动构造函数:

  struct bar { 
bar();
bar(const bar&)= delete;
bar(bar&&);
};

现在我需要使用 foo< bar> 。一个简单的用法:

  bar buz(){
return foo< bar>();
}

失败,

  main.cpp:在函数'bar buz()':
main.cpp:13:21:error:use of deleted function'bar :: bar(const bar&)'
return foo< bar>();
^
main.cpp:8:5:note:declaration here
bar(const bar&)= delete;
^ ~~




但是,如果我添加一些更复杂的解决方法:

  bar buz(){
return const_cast< bar&&>(std :: move(foo< bar>()))
}

它编译并且整个代码按预期工作,但我的真正的代码太)。



但是,它是安全的,或者我遇到一些未定义的行为?是否有更好的解决方法?






我已阅读并且理解关于返回 const from functions( 1 2 )和常见的答案似乎是在现代C ++中不鼓励返回 const 对象,但是我的问题不是关于它,而是关于如何解决外部库返回 const 对象。

解决方案

到未定义的行为。由于原始对象 C (一个临时)被声明为 const ,所以常量转换和修改是非法的, 。 (我假设,移动构造函数做一些修改movee)。



这就是说,它可能在您的环境中工作,我没有看到更好的解决方法。 p>

I have an external library which I can not modify. The library declares a template function that for some reason returns const non-reference object:

template<class C>
const C foo();

I have another external library which I can not modify too. The library declares a class that is non-copyable and has a move constructor from a non-const object only:

struct bar {
    bar();
    bar(const bar&)=delete;
    bar(bar&&);
};

Now I need to use foo<bar>. A simple usage:

bar buz() {
    return foo<bar>();
}

fails with

main.cpp: In function 'bar buz()':
main.cpp:13:21: error: use of deleted function 'bar::bar(const bar&)'
     return foo<bar>();
                     ^
main.cpp:8:5: note: declared here
     bar(const bar&)=delete;
     ^~~

which makes sense, and no simple workaround make the code compile.

However, if I add some more complex workaround:

bar buz() {
    return const_cast<bar&&>(std::move(foo<bar>()));
}

it compiles and the whole code work as expected (not only the simplified example above, but my real code too).

However, it is safe, or am I running into some undefined behavior? Is there any better workaround?


I have read and I understand questions about returning const from functions (1, 2), and the common answer there seems to be that returning const objects is discouraged in modern C++, but my question is not about it, but about how can I workaround the situation when an external library returns const object.

解决方案

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.

这篇关于const_cast和std :: move从非引用中删除const的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆