相关疑难解决方法(0)

const_cast和std :: move从非引用中删除constness

我有一个外部库,我无法修改.该库声明了一个模板函数,该函数由于某种原因返回const非引用对象:

template<class C>
const C foo();
Run Code Online (Sandbox Code Playgroud)

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

struct bar {
    bar();
    bar(const bar&)=delete;
    bar(bar&&);
};
Run Code Online (Sandbox Code Playgroud)

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

bar buz() {
    return foo<bar>();
}
Run Code Online (Sandbox Code Playgroud)

失败了

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;
     ^~~
Run Code Online (Sandbox Code Playgroud)

这是有道理的,并没有简单的解决方法使代码编译.

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

bar buz() {
    return const_cast<bar&&>(std::move(foo<bar>()));
}
Run Code Online (Sandbox Code Playgroud)

它编译并且整个代码按预期工作(不仅是上面的简化示例,而且我的真实代码也是如此).

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


我已阅读并理解有关返回的问题const从功能(1,2),以及常见的答案似乎是返回const对象在现代C++气馁,但我的问题是不是这件事,但我如何能解决该情况当外部库返回const对象时.

c++ const move-semantics c++11

20
推荐指数
2
解决办法
867
查看次数

标签 统计

c++ ×1

c++11 ×1

const ×1

move-semantics ×1