开发者

duplicating the same method with const?

开发者 https://www.devze.com 2023-02-15 12:28 出处:网络
InC++, I see this code. public: Ports& GetPorts(); const Ports& GetPorts() const; Why is it nece开发者_运维知识库ssary to have another method with const?

In C++, I see this code.

public: 
    Ports& GetPorts();
    const Ports& GetPorts() const;

Why is it nece开发者_运维知识库ssary to have another method with const? How can a compiler decide which method is called?


If you call x.GetPorts() and x is a non-const object, the first version will be called. If x is a const object, on the other hand, the second version will be called. That kind of code is saying "if the object is modifiable, allow the result of GetPorts() to be modified; if the object is const, don't allow the result to be modified." The compiler will prefer the first version if it matches; however, it will not be present if the object is const and so the second version will be used instead.


Because the first overload is not a const method you can't call it over temporaries and const objects. If you provide a const overload you essentially support const objects.

The compiler will use the const overload for const objects and the none-const overload for none-const objects.

It is usually not necessary to provide an overload if your function is const, because const functions are as safe as they get: they work for both const objects and none-const objects.


This is necessary only if you want to have different behavior for const and non-const objects. Otherwise the second version is enough. A design decision.

0

精彩评论

暂无评论...
验证码 换一张
取 消