我想问这有什么区别
Tv *television = new Tv();
和
Tv television = Tv();
第一个创建一个动态分配的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.