天天看點

c++ double轉string_C++核心準則:C.164:避免隐式轉換運算符

c++ double轉string_C++核心準則:C.164:避免隐式轉換運算符

C.164: Avoid implicit conversion operators

C.164:避免隐式轉換運算符

Reason(原因)

Implicit conversions can be essential (e.g., double to int) but often cause surprises (e.g., String to C-style string).

隐式轉換可以很重要(例如,double轉換為int),但經常會帶來意外的結果(例如,String轉換為C風格字元串)。

Note(注意)

Prefer explicitly named conversions until a serious need is demonstrated. By "serious need" we mean a reason that is fundamental in the application domain (such as an integer to complex number conversion) and frequently needed. Do not introduce implicit conversions (through conversion operators or non-explicit constructors) just to gain a minor convenience.

優先采用顯式命名轉換,直到發現必須重視的需求。我們通過“必須重視的需求”來表達在應用領域中非常本質(例如整數到複數的轉換)且經常遇到的原因。不要因為很小的便利而(通過轉換運算符或者非顯式構造函數)引入隐式轉換。

Example(示例)

struct S1 {    string s;    // ...    operator char*() { return s.data(); }  // BAD, likely to cause surprises};struct S2 {    string s;    // ...    explicit operator char*() { return s.data(); }};void f(S1 s1, S2 s2){    char* x1 = s1;     // OK, but can cause surprises in many contexts    char* x2 = s2;     // error (and that's usually a good thing)    char* x3 = static_cast(s2); // we can be explicit (on your head be it)}
           

The surprising and potentially damaging implicit conversion can occur in arbitrarily hard-to spot contexts, e.g.,

意外的、具有潛在破壞的隐式轉換可能在任何時候發生,而且難于發現。

S1 ff();char* g(){    return ff();}
           

The string returned by ff() is destroyed before the returned pointer into it can be used.

被ff()傳回的string對象會在傳回的指針被使用之前被銷毀。

Enforcement(實施建議)

Flag all conversion operators.

提示所有的轉換運算符。

原文連結:

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c164-avoid-implicit-conversion-operators

覺得本文有幫助?請分享給更多人。

更多精彩文章歡迎關注微信公衆号【面向對象思考】!

面向對象開發,面向對象思考!