[英]C++ mutable specifier
什么时候可以,什么时候不能调用可变变量?
int / float / bool值非常清楚。 但是,比方说数组。 如果我要向其添加元素,可以将其称为mutable
数组吗? 与std::vector
相同。
再举一个例子。 我有对象A,它保持对另一个对象B的引用(B&b)。对象B具有本机数组,我将重新分配/ std :: vector(在这种特殊情况下,我认为这是相似的)。 伪代码:
struct B{
std::vector<int> arr;
// int *arr; //Or this
void changeArr(){
arr.push_back(90);
}
}
struct A{
A(B &b) : b(b){};
mutable B &b; // is it ok to have it "mutable"?
//mutable B b; // or even this?
void fire() const{
b.arr.push_back(125);
// Or
b.changeArr();
}
}
我可以将B &b
称为可变吗?
更新
根据http://en.cppreference.com/w/cpp/language/cv :
可变-定义类的成员不影响该类的外部可见状态。
externally visible state of the class
什么? 当我增加数组大小,重新分配内容时会更改它吗? 如果没有,它什么时候发生变化?
让我们举两个经典的例子说明可变的地方:
class prime_caclulator {
private:
mutable std::vector<int> m_primes;
public:
get(int n) const {
// 1. If the nth prime is in m_primes, return it.
// 2. Otherwise, calculate the nth prime.
// 3. Store the nth prime in m_primes.
// 4. Return that prime.
}
};
在这里,我们有一个const函数get()
,无需更改此对象的内部状态即可计算第n个素数。 但是,跟踪先前计算的素数可能会有所帮助,以提高此对象的性能。
当调用get()
时,此内部状态(我们称为m_primes
)可能会更改,因此我们需要将其标记为可变的。 请注意,该对象的变化内容仅会更改此调用所花费的时间,而不是最终返回的内容。
template <typename T>
class thread_safe_queue {
private:
mutable std::mutex m_mutex;
std::queue<T> m_queue;
public:
size_t size() const {
std::lock_guard<std::mutex> lock(m_mutex);
return m_queue.size();
}
void push(T value) {
std::lock_guard<std::mutex> lock(m_mutex);
m_queue.push(value);
}
T pop() {
std::lock_guard<std::mutex> lock(m_mutex);
T top = m_queue.front();
m_queue.pop();
return top;
}
};
在这种情况下,如果我们没有可变的互斥体,那么我们将无法使size()
为const,因为我们在该函数的过程中修改了m_mutex
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.