前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则ES.64:使用T{e}记法构造对象

C++核心准则ES.64:使用T{e}记法构造对象

作者头像
面向对象思考
发布2020-05-29 14:58:03
5650
发布2020-05-29 14:58:03
举报
文章被收录于专栏:C++核心准则原文翻译

ES.64: Use the T{e}notation for construction

ES.64:使用T{e}记法构造对象

Reason(原因)

The T{e} construction syntax makes it explicit that construction is desired. The T{e} construction syntax doesn't allow narrowing. T{e} is the only safe and general expression for constructing a value of type T from an expression e. The casts notations T(e) and (T)e are neither safe nor general.

T{e}构造语法明确表达希望的构造方式。T{e}构造语法不允许窄化转换。T{e}是从表达式e构造T值的通用且唯一安全的方式。转换记法T(e)和(T)e既不安全也不通用。

Example(示例)

For built-in types, the construction notation protects against narrowing and reinterpretation

对于内置类型,这种构造方式可以防止窄化和数值的重新解释。

void use(char ch, int i, double d, char* p, long long lng)

代码语言:javascript
复制
{
    int x1 = int{ch};     // OK, but redundant
    int x2 = int{d};      // error: double->int narrowing; use a cast if you need to
    int x3 = int{p};      // error: pointer to->int; use a reinterpret_cast if you really need to
    int x4 = int{lng};    // error: long long->int narrowing; use a cast if you need to

    int y1 = int(ch);     // OK, but redundant
    int y2 = int(d);      // bad: double->int narrowing; use a cast if you need to
    int y3 = int(p);      // bad: pointer to->int; use a reinterpret_cast if you really need to
    int y4 = int(lng);    // bad: long long->int narrowing; use a cast if you need to

    int z1 = (int)ch;     // OK, but redundant
    int z2 = (int)d;      // bad: double->int narrowing; use a cast if you need to
    int z3 = (int)p;      // bad: pointer to->int; use a reinterpret_cast if you really need to
    int z4 = (int)lng;    // bad: long long->int narrowing; use a cast if you need to
}

The integer to/from pointer conversions are implementation defined when using the T(e) or (T)e notations, and non-portable between platforms with different integer and pointer sizes.

当使用T(e)或者(T)e记法进行整数和指针之间的转换时,结果随(编译器的,译者注)实现方式而定,并且在不同的整数和指针长度(64bit?32bit?)之间没有移植性。

Note(注意)

Avoid casts (explicit type conversion) and if you must prefer named casts.

避免类型转换(显式类型转换)。如果必须进行转换,则使用命名转换。

Note(注意)

When unambiguous, the T can be left out of T{e}.

如果目的明确,T可以脱离T{e}。

代码语言:javascript
复制
complex<double> f(complex<double>);

auto z = f({2*pi, 1});Note

The construction notation is the most general initializer notation.

构造记法是最常见的初始化记法。

Exception(例外)

std::vector and other containers were defined before we had {} as a notation for construction. Consider:

std::vector和其他容器在可以使用{}作为构造记法之前就已经存在了。考虑下面的代码:

代码语言:javascript
复制
vector<string> vs {10};                           // ten empty strings
vector<int> vi1 {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};  // ten elements 1..10
vector<int> vi2 {10};                             // one element with the value 10

How do we get a vector of 10 default initialized ints?

如何才能得到包含10个已经默认初始化了的元素的vector?

代码语言:javascript
复制
vector<int> v3(10); // ten elements with value 0

The use of () rather than {} for number of elements is conventional (going back to the early 1980s), hard to change, but still a design error: for a container where the element type can be confused with the number of elements, we have an ambiguity that must be resolved. The conventional resolution is to interpret {10} as a list of one element and use (10) to distinguish a size.

使用()而不是{}初始化元素个数是惯例(可以回溯到1980年代),很难改变,但依然是设计错误:当要素类型可能元素个数相混淆(例如整数,译者注)时,我们有必要消除歧义。习惯的做法是将{10}解释为只包含一个元素的列表,而(10)表示元素个数。

This mistake need not be repeated in new code. We can define a type to represent the number of elements:

这个错误没有必要在新代码中继续重复。我们可以定义一个用于表现元素个数的类型。

代码语言:javascript
复制
struct Count { int n; };

template<typename T>
class Vector {
public:
    Vector(Count n);                     // n default-initialized elements
    Vector(initializer_list<T> init);    // init.size() elements
    // ...
};

Vector<int> v1{10};
Vector<int> v2{Count{10}};
Vector<Count> v3{Count{10}};    // yes, there is still a very minor problem

The main problem left is to find a suitable name for Count.

剩下的主要问题是为Count找到一个合适的名称。

Enforcement(实施建议)

Flag the C-style (T)e and functional-style T(e) casts.

表示所有使用C风格(T)e和函数风格T(e)转换的代码。

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es64-use-the-tenotation-for-construction


觉得本文有帮助?请分享给更多人。

关注微信公众号【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2020-05-26,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • ES.64: Use the T{e}notation for construction
  • Reason(原因)
    • Exception(例外)
    相关产品与服务
    容器服务
    腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档