移动语义``this''?
想象以下情况:
class C {
public:
C(std::vector<int> data): data(data) {}
C sub_structure(std::vector<size_t> indices){
std::vector<int> result;
for(auto i : indices)
result.push_back(data[i]); // ***
return C(result);
}
std::vector<int> data;
};
C f(){
...
}
...
C c = f().sub_structure(...);
我猜想在标记***
的行中,制作了data
元素的副本,altough sub_structure
in即将被摧毁的对象。
如果我的呼叫类似于sub_structure(f(),...)
,我可以通过rvalue参考过载sub_structure
;但是,作为类方法,我不知道该怎么做,基本上是基于*此
是rvalue参考。
在不诉诸于全球功能的情况下,这种行为是否可以行为?
Imagine the following situation:
class C {
public:
C(std::vector<int> data): data(data) {}
C sub_structure(std::vector<size_t> indices){
std::vector<int> result;
for(auto i : indices)
result.push_back(data[i]); // ***
return C(result);
}
std::vector<int> data;
};
C f(){
...
}
...
C c = f().sub_structure(...);
I guess in the line marked ***
, copies of the elements of data
are made, altough sub_structure
is called on an object that's about to be destroyed.
If my call was something like sub_structure(f(), ...)
, I could overload sub_structure
by rvalue reference; however, as a class method, I'm not aware how to do that, basically based on if *this
is an rvalue reference.
Is such a behaviour possible without resorting to global functions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您是说价值类别过载吗?
不确定这是您的意思,但是如果正确解决问题,我会以这种方式:
demo https:https:https: //godbolt.org/z/5c89edmkv
这绝不是详尽的,人们可以轻松地将参考返回到const *上的const *the const&amp;超负荷,在非const等上复制。
Do you mean overloading on value category?
Not sure if this is what you mean, but if get your problem correctly, I'd go this way:
Demo https://godbolt.org/z/5c89edMKv
This is by no means exhaustive, one can easily return e.g reference to const *this on the const& overload, copy on non-const etc.