如何防止意外调用非const对象上的mutating函数? [英] How to prevent accidentally calling a mutating function on a non-const object?

查看:136
本文介绍了如何防止意外调用非const对象上的mutating函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个类型为myType的Object obj,并且我们想将它传递给函数Foo,它返回我们关于obj的一些有价值的信息。函数Bar是在哪里声明obj,并从中调用Foo,如下所示:

Suppose we have an Object obj of type myType, and we would like to pass it to function Foo, which returns us some valuable information about obj. function Bar is where obj is declared and from which Foo is being called like this:

void Bar ()
{

myType obj; //default constructor

string valuableInfo = Foo(obj); 

//do other stuff
//...

} //end of Bar()

这段代码当然不会说太多关于Foo是否以obj作为引用或值,以及Foo是否以任何方式修改obj。

This snippet of code of course does not say much about whether Foo takes obj as a reference or as value, and whether or not Foo modifies obj in any way.

当然如果Foo使用obj作为值或const引用,我们不会有任何问题。

of course if Foo takes obj as value or const reference, we wont have any issues.

string Foo (const myType & input); //this is fine 
string Foo (myType input); //so is this

,但我们不能保证这一点!函数签名很可能是

but we are not guaranteed this! the function signature could very well be

string Foo (myType & input); //asking for trouble!!

但是它非常不方便检查我们想要传递obj的每个函数的签名,所以我们如何指定我们只想将我们的对象传递给不承诺修改它的函数?

but it is awfully inconvenient to check the signature of every function we would want to pass obj to, so how can we specify that we want to only pass our object to functions that promise not to modify it?

当然一种方法是将obj声明为const,但问题这种方法是我们失去灵活性。如果我们想在调用Foo(obj)后在Bar()中修改obj?

of course one approach is to declare obj as const, but the problem with this approach is that we lose flexibility. what if we want to modify obj in Bar() after calling Foo(obj)?

void Bar ()
{

const myType obj; //default constructor

string valuableInfo = Foo(obj); //compiler will complain if Foo's signature doesnt match

//we can't modify obj here :(
//...

} //end of Bar()

明显但不好的解决方案是:

The obvious but bad solution is to do this:

void Bar ()
{

myType obj; //default constructor

const myType immutableObj {obj}; //copy ctr call
//this is expensive and not recommended if obj is big! want to avoid

string valuableInfo = Foo(immutableObj); //will get the valuable Info risk free
// compiler will complain if Foo has inappropriate signature

//do other stuff
//...

} //end of Bar()

那么什么是最好的解决方案?静态断言Foo对于我们传入的对象是非侵入性的?我们可以暂时使obj const(而不必创建一个新的const对象)或其他效果?

so What is the best solution here? is there a way to statically assert that Foo is non invasive to the object we pass in? can we temporarily make obj const (without having to create a new const object) or something to that effect?

推荐答案

Foo(static_cast<const myType&>(obj));

这篇关于如何防止意外调用非const对象上的mutating函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆