【发布时间】:2014-03-26 15:56:25
【问题描述】:
基本上,我有以下情况。注意:void* 用于表示任意数据,在实际应用中是强类型的。
class A
{
public:
//uses intermediate buffer but doesn't change outward behavior
//intermediate buffer is expensive to fill
void foo(void* input_data);
//uses intermediate buffer and DOES explicitly change something internally
//intermediate buffer is expensive to fill
void bar(void* input_data);
//if input_data hasn't changed since foo, we can totally reuse what happened in foo
//I cannot check if the data is equal quickly, so I allow the user to pass in the
//assertion (put the honerous on them, explicitly tell them in the comments
//that this is dangerous to do, ect)
void bar(void* input_data, bool reuse_intermediate);
private:
void* intermediate_buffer_;
void* something_;
};
因此,为了 const 的正确性,intermediate_buffer_ 永远不会暴露,因此它符合使用 mutable 变量的定义。如果我从未重用过这个缓冲区,或者我在使用缓存值之前检查了相等的 input_data,那将是故事的结尾,但由于重用_中间体,我觉得我暴露了一半,所以我不确定是否或者以下是否有意义。
class A
{
public:
//uses intermediate buffer but doesn't change something
//intermediate buffer is expensive to fill
void foo(void* input_data) const;
//uses intermediate buffer and DOES explicitly change something internally
//intermediate buffer is expensive to fill
void bar(void* input_data);
//if input_data hasn't changed since foo, we can totally reuse what happened in foo
//I cannot check if the data is equal quickly, so I allow the user to pass in the
//assertion (put the honerous on them, explicitly tell them in the comments
//that this is dangerous to do, ect)
void bar(void* input_data, bool reuse_intermediate);
//an example of where this would save a bunch of computation, though
//cases outside the class can also happen
void foobar(void* input_data)
{
foo(input_data);
bar(input_data,true);
}
private:
mutable void* intermediate_buffer_;
void* something_;
};
想法?
【问题讨论】:
-
mutable似乎是合理的。但也许只是将其重命名为bar(void* input_data, bool fast),而不是暗示存在中间体。如果您不希望用户伤害自己,或者将其设为private而不是public。 -
使用
T而不是void会更清楚。void *具有特殊语义。