Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Why does C++ clearly define a single-parameter constructor in the default state?

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces the knowledge of "why C++ clearly defines a single-parameter constructor by default". Many people will encounter such a dilemma in the operation of actual cases. then let the editor lead you to learn how to deal with these situations! I hope you can read it carefully and be able to achieve something!

C.46: a single parameter constructor Reason is clearly defined by default (reason)

Avoid unexpected conversions.

Example, bad (negative example)

Class String {

Public:

String (int); / / BAD

/ /...

}

String s = 10; / / surprise: string of size 10Exception (exception)

If you do need an implicit type conversion from constructor arguments like class types, do not use the explicit keyword.

Class Complex {

Public:

Complex (double d); / / OK: we want a conversion from d to {d, 0}

/ /...

}

Complex z = 10.7; / / unsurprising conversion Exception (exception)

Copy and move constructors should not be defined as explicit, because type conversions will not be performed. Explicit copy / move constructors make it difficult to pass parameters and return results by value.

Enforcement (implementation recommendations)

(simple) the constructor with unique parameters should be defined as explicit. Well-defined non-explicit single-argument constructors are rare in most code. Give a warning for all situations that are not in the positive list.

This is the end of the content of "Why C++ clearly defines a single-parameter constructor by default". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report