[英]Undefined reference for boost::mutex in struct
我想将boost :: mutex用于struct Cell的功能添加 。 这是Detector.h中我的结构的定义
class Detector {
private:
struct Cell{
static boost::mutex mutex_;
double energy;
double sqrt_energy;
int histories;
inline Cell(): energy(0.f), sqrt_energy(0.f), histories(0.f) {
boost::mutex mutex_; //I tried with and without this line
};
inline void add(double new_energy) {
mutex_.lock();
energy += new_energy;
sqrt_energy += new_energy*new_energy;
++histories;
mutex_.unlock();
};
};
typedef std::vector<Cell> CellVector;
CellVector EnergyPrimary;
}
我使用我的函数在Cell的向量上添加到Detector.cpp中。
Dectetor::Detector() : {
nVoxelX=1024;
nVoxelY=1024;
size=nVoxelX*nVoxelY;
EnergyPrimary=CellVector(size);
}
void Detector::Score(int cellID, double new_energy) {
EnergyPrimary[cellID].add(new_energy);
}
当我尝试编译它时,mutex_.lock()和Mutex_.unlock()出现未定义的引用错误。 但是,当我用类似的功能重载运算符+ =时(以及当我调用EnergyPrimary [cellID] .energy + = new_energy;时),为什么它能正常工作?
inline bool operator+= (double new_energy) {
mutex_.lock();
energy += new_energy;
mutex_.unlock();
return false;
};
您已将mutex_
定义为类的静态成员,这意味着它不是每个实例的成员。 因此,您不能在构造函数中初始化。 相反,必须在源文件中初始化它(对于您而言,很可能是Detector.cpp
。
初始化代码应为:
boost::mutex Detector::Cell::mutex_;
如果您不希望它成为静态成员(每个单元要一个互斥锁),请删除static
限定符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.