简体   繁体   English

用C ++创建对象

[英]Object create in C++


I have a little question about a code example in C++. 我对C ++中的代码示例有一点疑问。

vector<Cat> v;
Cat c;
v.push_back(c);
Cat d = v[0];

In this piece of code, how many objects are created? 在这段代码中,创建了多少个对象?

At least three: 至少三个:

vector<Cat> v;
Cat c;  // default construction
v.push_back(c); // copy construction of v[0] from c
Cat d = v[0];  // copy construction of d from v[0]

Edit: Note that I only count Cat objects here, because it doesn't make sense to ask how many objects in total are created, because that would be implementation specific (how is std::vector implemented? What does Cat do? ...) 编辑:请注意,我在这里只计算Cat对象,因为询问总共创建了多少个对象是没有意义的,因为那将是特定于实现的(如何实现std::vectorCat做什么? 。)

Add some logging to the constructor of Cat and test it yourself: 将一些日志记录添加到Cat的构造函数中并自行测试:

class Cat
{
  Cat() 
  {
    std::cout<<"Constructing a Cat"<<std::endl;
  }
  Cat( const Cat & cat )
  {
    std::cout<<"Copy Constructing a Cat"<<std::endl;
  }
};

Here's what I get: http://codepad.org/Pzs9kOlH 这是我得到的: http//codepad.org/Pzs9kOlH

Note that under certain conditions the compiler is free to remove chunks of code that do nothing. 请注意,在某些情况下,编译器可以自由删除不执行任何操作的代码块。 So some copies may get removed. 因此可能会删除一些副本。 With a hypothetical very agressive compiler it might notice that nothing is done by your code and completely strip out any such constructions altogether. 使用假设的非常激进的编译器,它可能会注意到您的代码没有完成任何操作,并完全删除任何此类构造。 Since my constructors now change the output the compiler is less free to remove calls to them. 由于我的构造函数现在更改输出,因此编译器不太可以自由删除对它们的调用。

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

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