非成员函数是否可以返回const值? [英] Is it possible for a non-member function to return a const value?
问题描述
如果是,怎么办?这个问题甚至有意义吗?
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.
推荐答案
const MyClass foo();
有效,但返回const值没有意义-无论如何它都会被复制。
const MyClass foo();
is valid, but returning a const value doesn't make sense - it's copied anyway.
您可以返回例如const引用: const MyClass& foo();
也完全有效。
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.
如果您正在考虑 const MyClass * foo();
,则const更有意义-用户将无法修改指向 MyClass
实例的指针。
If you're thinking about const MyClass * foo();
then the const is more meaningful - the user will not be able to modify the pointed to MyClass
instance.
这篇关于非成员函数是否可以返回const值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!