c ++中的类实例

use*_*497 -2 c++ class

我想问一下这有什么区别

Tv *television = new Tv();
Run Code Online (Sandbox Code Playgroud)

Tv television = Tv();
Run Code Online (Sandbox Code Playgroud)

jua*_*nza 5

第一个创建动态分配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.
Run Code Online (Sandbox Code Playgroud)

第二个创建由副本初始化自动分配 .对象的持续时间是自动的.根据语言规则,例如在退出范围内,它会被确定性地销毁:TvTv

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

"exiting scope"也可以指包含对象的类的对象的生命周期结束Tv:

struct Foo {
  Tv tv;
}

....
{
  Foo f;
} // f is destroyed, and f.tv with it.
Run Code Online (Sandbox Code Playgroud)