向量中元素的默认构造

发布于 2024-07-20 07:19:29 字数 679 浏览 7 评论 0原文

在阅读这个问题的答案时,我对向量中对象的默认构造有疑问。 为了测试它,我编写了以下测试代码:

struct Test
{
    int m_n;

    Test(); 

    Test(const Test& t);

    Test& operator=(const Test& t);
};

Test::Test() : m_n(0)
{
}

Test::Test(const Test& t)
{
    m_n = t.m_n;
}

Test& Test::operator =(const Test& t)
{
    m_n = t.m_n;
    return *this;
}


int main(int argc,char *argv[])
{
    std::vector<Test> a(10);
    for(int i = 0; i < a.size(); ++i)
    {
        cout<<a[i].m_n<<"\n";
    }

    return 0;
}

果然,在创建向量对象时调用了 Test structs 默认构造函数。 但我无法理解的是,STL 如何初始化我创建基本数据类型向量(例如整数向量)的对象,因为它有默认构造函数? 即向量中的所有整数的值如何均为 0? 不应该是垃圾吗?

While reading the answers to this question I got a doubt regarding the default construction of the objects in the vector. To test it I wrote the following test code:

struct Test
{
    int m_n;

    Test(); 

    Test(const Test& t);

    Test& operator=(const Test& t);
};

Test::Test() : m_n(0)
{
}

Test::Test(const Test& t)
{
    m_n = t.m_n;
}

Test& Test::operator =(const Test& t)
{
    m_n = t.m_n;
    return *this;
}


int main(int argc,char *argv[])
{
    std::vector<Test> a(10);
    for(int i = 0; i < a.size(); ++i)
    {
        cout<<a[i].m_n<<"\n";
    }

    return 0;
}

And sure enough, the Test structs default constructor is called while creating the vector object. But what I am not able to understand is how does the STL initialize the objects I create a vector of basic datatype such as vector of ints since there is default constructor for it? i.e. how does all the ints in the vector have value 0? shouldn't it be garbage?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

乖乖兔^ω^ 2024-07-27 07:19:30

它使用与 int 的默认构造函数等效的功能,即对它们进行零初始化。 您可以明确地执行此操作:

int n = int();

将 n 设置为零。

请注意,只有在给定向量初始大小的情况下才使用和需要默认构造。 如果你说:

vector <X> v;

不要求X有默认构造函数。

It uses the equivalent of the default constructor for ints, which is to zero initialise them. You can do it explicitly:

int n = int();

will set n to zero.

Note that default construction is only used and required if the vector is given an initial size. If you said:

vector <X> v;

there is no requirement that X have a default constructor.

别再吹冷风 2024-07-27 07:19:30
std::vector<Type> a(10);        // T could be userdefined or basic data type

Vector 基本上会为其指向的类型调用 default

  • 如果它是像 int 这样的基本数据类型,则 Type()
    double 则存在 int(), double() { int() 将获取值 0}
  • 如果用户定义的数据类型则
    将调用默认构造函数。
std::vector<Type> a(10);        // T could be userdefined or basic data type

Vector basically calls default for the type to which it points: Type()

  • if it is basic data type like int,
    double are there then int(), double() { int() will get value 0}
  • if the user defined data type then
    default constructor would be called.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文