Pass by const class reference

void foo(const ClassName &name) { ... } 

How do I access the class instance name method?

name.method() does not work. then I tried:

 void foo(const ClassName &name) { ClassName temp = name; ... .... } 

I can use temp.method, but after foo has been executed, the original name is screwed, any idea? BTW, the member variable of the name was not corrupted, but it was a member of the class subclass of the class, screwed up.

+4
source share
2 answers

If I understand you correctly, you want to call name.method() inside foo() , and the compiler does not allow you. Is ClassName::method() non-constant method? Since name declared as a const parameter to foo() , you can call const functions on it.

Update: if ClassName::method() not a constant, but does not actually change the state, it would be best, of course, to make it const . If you cannot for some reason, I see the following ways:

  • (the obvious way, as @Naveen pointed out - thanks :-) to declare name as a parameter of a non-constant method.
  • create a non-constant copy of name and call method on it - as you did. However, this only works if the assignment operator and / or copy constructor are correctly implemented for ClassName . However, you write "after foo was executed, the original name is screwed on", which is a very vague description, but it can be interpreted so that copying does have some unwanted side effects on name , which suggests that these functions do not are implemented correctly or in general.
  • (disgusting way) discards a constant using const_cast - this really should be the last resort, and only if you are sure that ClassName::method() does not actually change any state.

Update2 , to the comment @AKN - an example of a constant deviation:

 void foo(const ClassName &name) { ClassName& temp = const_cast<ClassName&>(name); ... .... } 
+4
source

Following the description you provided, it looks like method() in ClassName - this is a non-constant method. If you try to call the non-const method on the comp compiler of the const object, this will throw an error. When you did ClassName temp = name; , you created a copy of the variable in a temporary non-constant temp object. You can call any method for this object, but since it is a copy, modifications made to this object will not be reflected in the name object.

EDIT

The best way to solve this problem is to make ClassName::method const if it does not change any member variables. If so, then you should not accept your parameter in the foo function as const-reference. You must accept the parameter as a non-constant reference.

+6
source

Source: https://habr.com/ru/post/1310461/


All Articles