-2

我想问这有什么区别

Tv *television = new Tv();

Tv television = Tv();
4

1 回答 1

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.

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

{
  // 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.
于 2012-09-22T15:44:46.270 回答