返回 const auto 对象——以及 Qt 隐式共享
所以众所周知,这段代码是没有意义的:
const int foo()
{
int n = // do computation...;
return n;
}
因为无论如何,当它被复制时返回“const int”是什么意思?
但是对于像 Qt 容器这样具有隐式共享 (COW) 的类,这又有意义了吗?考虑一下:
const QList<mytype> get_list()
{
QList<mytype> lst;
// do stuff to fill list;
return lst;
}
现在我可以这样做:
const QList<mytype> mylst = get_list();
由于 Qt 对容器具有隐式共享,因此它应该可以正常工作,因为 return lst
并不真正复制列表的内容,只是增加引用计数和 const 确保我无法修改它(如果
get_list
由于某种原因想要确保它,或者需要它是 const
方法本身)。我的想法在这里正确吗?
So it is known this code is not sensical:
const int foo()
{
int n = // do computation...;
return n;
}
Because what meaning is to return "const int" when it is copied anyway?
But with classes with implicit sharing (COW) like Qt containers, it makes sense again? Consider:
const QList<mytype> get_list()
{
QList<mytype> lst;
// do stuff to fill list;
return lst;
}
Now I can do:
const QList<mytype> mylst = get_list();
Since Qt has implicit sharing for containers, it should work OK because return lst
doesn't really copy the contents of list, just increase refcount, and const
make sure I can't modify it (if get_list
want to ensure it for some reason, or needs it to be const
method itself). Is my thinking correct here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我无法理解整个问题。但是,以上部分不正确。您仅从函数返回一个
const
值,并且它不强制接收端也为const
。因此,允许从mylst
中删除const
,并且它再次变得可修改。I couldn't understand the whole question. But, above part is not correct. You are returning just a
const
value from the function and it doesn't mandate the receiving end also to be aconst
. So removingconst
frommylst
is allowed and it again becomes modifiable.