5

I recently started trying to enforce const correctness in my code. In a function definition, I feed a constant pointer to a constant object of the class LorentzM:

void AnalysisObject::SetOwnedPointer(const int maptotree_In, const LorentzM* const momentum_In){ 
owned_pp4_original.reset(momentum_In); 
maptotree=maptotree_In;
}

where owned_pp4_original is

shared_ptr<LorentzM> owned_pp4_original;

I do this, because this function, SetOwnedPointer, should never change the LorentzM* momentum_In nor should it change the object that it points to, so constant pointer to constant object it is.

However, a shared_ptr is created to the object where momentum_In points to, and I do want to use this shared_ptr to change the object later on:

void ChangeLorentzM(const double px, const double py, const double pz, const double E){
owned_pp4_original->SetPxPyPzE(px,py,pz,E); //THIS CHANGES THE OBJECT
}

So, on one hand, to be able to do:

owned_pp4_original.reset(momentum_In); 

owned_pp4_original should be a shared_ptr<const LorentzM>

but then, I wouldn't be able to change the object through it.

What's wrong in this picture?

thanks a lot.

4

1 回答 1

5

I do this, because this function, SetOwnedPointer, should never change the LorentzM* momentum_In nor should it change the object that it points to, so constant pointer to constant object it is.

That's not reason enough. The function may not change the object directly, but it is granting another object (the shared_ptr) rights to modify the object. It can't grant rights that it doesn't have itself. So change it to a pointer to a non-const object.

It's the same thing, for example, if you have a class that has a non-const reference member. You need to pass a non-const object to its constructor, even if the constructor does not itself modify the object. The constructor needs to grant the object's reference member rights to modify the object, and it can't do that if it does not itself have those rights.

于 2012-12-14T14:28:07.403 回答