奇怪的c ++代码片段 [英] Weird c++ code snippet

查看:268
本文介绍了奇怪的c ++代码片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个片段:

 模板< class T& 
类VECTOR_2D
{
public:
T x,y;

VECTOR_2D()
:x(T()),y(T())
{}
}

解决方案

在构造函数中初始化x和y是什么? div>

x y 已复制初始化



从C ++ 03标准,§8.5/ c> T 7:


一个对象的初始值是一个空的圆括号,即()

并从§8.5/ 5开始:


em> value-initialize 类型 T 的对象表示:




  • 如果 T 是一个具有用户声明的构造函数的类类型,则调用 T 的默认构造函数如果 T 没有可访问的默认构造函数,则初始化是错误的);

  • 如果 T 是没有用户声明的构造函数的非联合类类型,则 T 的每个非静态数据成员和基类组件都是值初始化的;

  • 如果 T 是数组类型,则每个元素都被初始化;

  • 否则,对象是零初始化


要初始化<$ c $ < c> T 表示:




  • 如果 T 一个标量类型,对象设置为 0 (零)转换为 T ;

  • 如果 T 是非联合类类型,每个非静态数据成员和每个基类子对象都是零初始化的;

  • 如果 T 是联合类型,对象的第一个命名数据成员)是零初始化的;

  • if T 是一个数组类型,每个元素都是零初始化的;

  • 如果 T 是引用类型,不执行初始化。






$ b b

x(T()),y(T())可以替换为 x c $ c>直接替换为value-initialize x y 。在大多数情况下,这将实现相同的净效果(假设 T 是可复制构造的),但在某些情况下,这将更有效,因此作为一般规则,


I have this snippet:

template<class T>
class VECTOR_2D 
{
public:
    T x,y;

    VECTOR_2D() 
        :x(T()),y(T())
    {}
}

What are x and y initialized to in the constructor?

解决方案

x and y are copy-initialized to T's value-initialized value.

From the C++03 standard, §8.5/7:

An object whose initializer is an empty set of parentheses, i.e., (), shall be value-initialized.

And from §8.5/5:

To value-initialize an object of type T means:

  • if T is a class type with a user-declared constructor, then the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);
  • if T is a non-union class type without a user-declared constructor, then every non-static data member and base-class component of T is value-initialized;
  • if T is an array type, then each element is value-initialized;
  • otherwise, the object is zero-initialized

To zero-initialize an object of type T means:

  • if T is a scalar type, the object is set to the value of 0 (zero) converted to T;
  • if T is a non-union class type, each nonstatic data member and each base-class subobject is zero-initialized;
  • if T is a union type, the object’s first named data member) is zero-initialized;
  • if T is an array type, each element is zero-initialized;
  • if T is a reference type, no initialization is performed.


x(T()),y(T()) could be replaced with x(),y() to instead value-initialize x and y directly. In most circumstances this will achieve the same net effect (assuming T is copy constructable), but in some cases this will be more efficient, so as a general rule this approach should always be preferred.

这篇关于奇怪的c ++代码片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆