Are link members good practice? Are constants?

The employee and I discuss whether members compete or refer correctly. const and referenced members make the class non-copyable and motionless unless you write your own copy and move statements that ignore referenced or constant members. I cannot find a case where ignoring copying or moving certain members just because they are links or const makes sense.

I think that a stationary object very rarely sounds logical, and this is a choice that is only related to whether the class is an invariant of location . A noncopyable object is much more common, but the choice to make a noncopyable class is related to whether it has a resource that is not logically copyable if it is a sole proprietorship, etc. I can’t think of a reason, the only feature is that it has a referenced or const member or it won’t mean that the class should have one of these attributes (not copyable or fixed)

Should they ever be used? Should someone and not another? What are some examples?

+4
source share
1 answer

I can’t think of a reason, the only trait of having a reference or const member, or it won’t mean that the class must have one of these traits (not copyable or fixed)

I think it's wrong.

The presence of a const data member or a reference data element does not make the class non-copyable: it simply makes it impossible to assign it or move from it in a destructive way.

This is because the destructive move operation does not sound for objects or const links: it will be against their semantics, since the state of a const object should never change, and the links cannot be disconnected.

However, the fact that X not assignable for copying or forwarding does not jeopardize the ability to create copies of these objects, which - as you indicate - is a sound operation. For example, the following program will compile:

 struct X { X() : x(0), rx(x) { } const int x; const int& rx; }; int main() { X x; X x1 = x; // Copy-initialization (copy-constructs x1 from x) X x2 = X(); // Copy-initialization (copy-constructs x2 from a temporary) } 

The compiler implicitly generates a copy constructor for you, and movements will degenerate into a copy. If this degeneration of moving into a copy is not suitable for the semantics of your class, you may not have const or reference elements.

+5
source

All Articles