非成员函数是否可以返回 const 值?
如果是这样,怎么办?这个问题还有道理吗?
就我而言,调用者修改返回的对象是没有意义的,因此我想将其标记为不可修改。
If so, how? Does this question even make sense?
In my case it would make no sense to have the returned object modified by the caller, so I want to mark it as non-modifiable.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
const MyClass foo();
是有效的,但返回 const 值没有意义 - 无论如何它都会被复制。您可以返回例如 const 引用:const MyClass & foo(); 也是完全有效的。但这并不妨碍用户进行复制。
如果您正在考虑 const MyClass * foo(); 那么 const 更有意义 - 用户将无法修改指向的
MyClass
实例。const MyClass foo();
is valid, but returning a const value doesn't make sense - it's copied anyway.You can return e.g. a const reference:
const MyClass & foo();
is also perfectly valid. This doesn't prevent the user from making a copy though.If you're thinking about
const MyClass * foo();
then the const is more meaningful - the user will not be able to modify the pointed toMyClass
instance.这是可以做到的,但不一定有多大意义。如果您按值返回某些内容,则调用者收到的只是您返回的内容的临时副本,因此他们通常无法修改它。
当您返回参考文献时,它会更有意义;如果(例如)您通过引用收到某些内容,并返回对该内容的引用,那么如果您收到的内容是 const 限定的,那么您可能希望对返回的内容进行 const 限定。这通常意味着为 const/非常量参数重载函数,每个参数都有匹配的返回类型。
编辑:这可以处理(例如)C 中使用 strstr 和 strchr 等函数出现的问题,这些函数采用 const 限定的指针,但返回一个指针相同的数据(在本例中为字符串)不 const 限定。在 C 中,这些在类型系统中形成了一个漏洞,您可以在其中意外地修改(或至少尝试)一些本来应该是 const 的东西,而无需任何(可见的)强制转换。
It can be done, but doesn't necessarily make a lot of sense. If you return something by value, what the caller receives is a temporary copy of what you returned, so they normally can't modify it anyway.
It can make more sense when you're returning a reference; if (for example) you receive something by reference, and return a reference to the same, you probably want to const-qualify what you return if what you received was const-qualified. This typically means overloading your function for const/non-const parameter, each with matching return type.
Edit: This can deal with (for example) a problem that arose in C with functions like
strstr
andstrchr
, which take a const-qualified pointer, but return a pointer into the same data (string, in this case) that's not const-qualified. In C, these form a hole in the type system, where you can accidentally modify (or at least try to) something that was intended to be const, without any (visible) cast.