简体   繁体   English

向量和原始类型初始化

[英]vector and primitive type initialisation

I've learned that if you declare for example an int in the global scope, 我了解到,如果您在全局范围内声明一个int,

int x; int x; //defaults to 0; //默认为0;

and in the local scope, 在当地范围内

void f() {
    int x; //undefined
}

However if we use a vector either in the global or local scope: 但是,如果我们在全局或局部范围内使用向量:

vector<int> v(3); vector <int> v(3); //initialise v to {0,0,0} using int's default constructor. //使用int的默认构造函数将v初始化为{0,0,0}。

We can default initialise int like vector's elements in the local scope by doing this: 通过执行以下操作,我们可以在本地范围内默认初始化int,例如vector的元素:

int x = int(); int x = int(); //defaults to 0 //默认为0

I think if we use int's default constructor it's allocated in the heap. 我认为,如果我们使用int的默认构造函数,那么它将在堆中分配。

  1. Why can't a primitive type be default initialised in the local scope like T x;? 为什么不能在Tx;之类的本地范围内默认初始化原始类型? Or 要么
  2. In the local scope, why does vectors (dunno about other containers) use the element's default constructor and not leave them uninitialised just like an int declaration? 在本地范围内,为什么矢量(其他容器不知道)使用元素的默认构造函数,而不像int声明那样不对它们进行未初始化?
  3. What are the benefits of current approach on those two types? 当前的方法对这两种类型有什么好处? Why are they initialised in different ways? 为什么用不同的方式初始化它们? Is this about performance? 这是关于性能的吗?

It's like this for "performance" reasons, because the C++ folks wanted the C folks back in the 1980's to not have any reason to complain about "paying for what we don't need." 之所以这样,是因为出于“性能”的原因,因为C ++人士希望C人士早在1980年代就没有任何理由抱怨“为我们不需要的东西付钱”。 That's one of the tenets of C++, to not pay (run-time) costs for things you don't use. 这是C ++的宗旨之一,它不为不使用的东西支付(运行时)费用。 So the old-style POD types are uninitialized by default, though classes and structs with constructors always have one of those constructors called. 因此,尽管具有构造函数的类和结构始终具有被调用的那些构造函数,但是默认情况下,老式POD类型是未初始化的。

If I were specifying it today, I'd say that int x; 如果我今天指定它,我会说int x; in local scope would be default-initialized (to 0), and if you wanted to avoid that you could say something like int x = std::noinit; 在本地范围内将被默认初始化(为0),如果您想避免这种情况,可以说int x = std::noinit; . It's far too late for this now, but I have actually done it in some class types when performance mattered a lot: 现在这还为时已晚,但是当性能非常重要时,我实际上已经在某些类类型中完成了它:

class SuperFast
{
  struct no_init_t {};
public:
  no_init_t no_init;
  SuperFast() : x(0), y(0) {}
  SuperFast(no_init_t) {}

private:
  int x, y;
};

This way, default construction will give a valid object, but if you have a serious reason to need to avoid this, you can. 这样,默认构造将提供有效的对象,但是如果您有严重的理由需要避免这种情况,则可以这样做。 You might use this technique if you know you will soon overwrite a whole bunch of these objects anyway--no need to default-construct them: 如果您知道很快就会覆盖全部这些对象,则可以使用此技术-无需默认构造它们:

SuperFast sf(SuperFast::no_init); // look ma, I saved two nanoseconds!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM