复数返回值的常量正确性
结构体 Foo { 字符 * 数据指针; };
class ISomeInterface {
public:
Foo GetFoo( ) const;
Foo GetFoo( );
};
Foo::DataPtr
是指向ISomeInterface
对象内部缓冲区的指针。有没有办法确保 const 版本的 ISomeInterface::GetFoo
返回的 Foo::DataPtr
是 const char *
?
struct Foo {
char * DataPtr;
};
class ISomeInterface {
public:
Foo GetFoo( ) const;
Foo GetFoo( );
};
The Foo::DataPtr
is a pointer to an internal buffer of the object behing ISomeInterface
. Is there a way to make sure that the Foo::DataPtr
returned by the const version of ISomeInterface::GetFoo
is a const char *
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你需要一个
为此 。 C++ 中的 const 不具有传递性。 (这也是为什么你有
iterator
和const_iterator
。)You need a
for this. The const in C++ is not transitive. (this is also why you have
iterator
andconst_iterator
.)结构
与结构不同,
因此您无法区分您想要的方式。
您可以使 const
GetFoo()
返回一个 constFoo
对象(我怀疑这不是您想要的,因为它会使所有成员变量都为 const),或者 make另一个带有const char * DataPtr
的结构(比如FooConst
),它在 const 调用时返回。A struct
is not the same as
so you cannot differentiate how you would like.
You could make the const
GetFoo()
return a constFoo
object (which I suspect is not what you want, as it will make all the member variables const), or make another struct with aconst char * DataPtr
(sayFooConst
) which is returned on the const call.您可以尝试更改
Foo
的设计,并将对DataPtr
的访问“隐藏”在函数后面。例如:提供定义哪些操作是 const 和哪些操作不是 const 的函数,可以避免重复您的
Foo
并获得您似乎想要的 const 正确性限制。You could try to change the design of your
Foo
and 'hide' the acess toDataPtr
behind functions. For instance:Providing functions that define which operations are const and those that are not you can avoid duplicating your
Foo
and obtain the const-correctness restrictions you seem to be aiming for.