在C类的实例++(Instance of class in c++)

2019-09-22 18:58发布

我woud要问的是什么这之间的区别

Tv *television = new Tv();

Tv television = Tv();

Answer 1:

第一种创建一个动态分配的Tv并将其绑定到一个指针到Tv 。 在持续时间Tv的对象是你的控制之下:你决定何时通过调用摧毁它delete就可以了。

new Tv(); // creates dynamically allocated Tv and returns pointer to it
Tv* television; // creates a pointer to Tv that points to nothing useful
Tv* tv1 = new Tv(); // creates dynamicalls allocated Tv, pointer tv1 points to it.

delete tv1; // destroy the object and deallocate memory used by it.

第二个创建一个自动分配的 Tv通过拷贝初始化 。 所述的持续时间Tv对象是自动的。 它被摧毁确定性,根据语言,例如在退出范围的规则:

{
  // copy-initializaiton: RHS is value initialized temporary.
  Tv television = Tv(); 
} // television is destroyed here.

“退出范围”也可以指的是包含一个类的一个对象的寿命结束Tv对象:

struct Foo {
  Tv tv;
}

....
{
  Foo f;
} // f is destroyed, and f.tv with it.


文章来源: Instance of class in c++
标签: c++ class