问题描述
在C ++中(我使用QT)我可以创建一个QString类的实例两种方式:
In C++ (I use QT) I can create an instance of QString class two ways:
QString str = "my string";
方法2
method 2
QString *str = new QString("my string");
我知道这是与指针有关。所以我的问题是:
I know this is to do with pointers. So my questions are:
- 两者之间的区别是什么?
- 依照?
- 在方法2中使用方法1时是否正确以及何时正确使用方法2?
-
delete str;
。如何在使用方法1时删除str
变量?
- what is the difference between the two?
- which method should I stick to?
- when is it correct to use method 1 and when is it correct to use method 2?
- in method 2 I can destroy the object by calling
delete str;
. How can I delete thestr
variable when using method 1?
/ p>
Thanks
推荐答案
-
主要有不同的生命周期:方法2中创建的对象将生存任意长直到你调用delete;在方法1中,它将在堆栈上创建,并在从函数调用(如果有)返回时被销毁。第二种方法2需要更多的工作,因为非平凡的内存管理。
primarily they have different lifetimes: the object created in method 2 will live arbitrarily long until you call delete; in method 1 it will be created on the stack and be destroyed upon return from the function call (if any). secondarily method 2 requires more work because of non-trivial memory management.
使用匹配你想要的生命周期的方法。如果方法1的生命周期足够好,您不使用方法2,因为它需要内存管理的开销。如果你可以重构你的程序,以便你可以做方法1,同时改善设计,这将更有效率和优雅。
use the method that matches the lifetime you want. if the lifetime of method 1 is good enough for you do not use method 2 because it entails the overhead of memory management. if you can restructure your program so that you can do with method 1 while also improving on the design, that will be more efficient and elegant.
请参阅2。以上。特别是使用方法1并存储指向对象并在其生命周期之后访问对象的指针是一个陷阱。这也是可能的方法2,但显式破坏聚焦程序员的注意力(但仍然是因为生命是不直接,它是一个可能的陷阱)方法2的一个陷阱忘记删除它导致内存泄漏(或删除它
see 2. above. in particular, using method 1 and storing a pointer to the object and accessing it after its lifetime is a pitfall. this is also possible with method 2 but the explicit destruction focuses the programmer's attention on it (but still because the lifetime is not straightforward it is a likely pitfall) a pitfall with method 2 is forgetting to delete it causing a memory leak (or deleting it too early and referring to it as described earlier in this paragraph)
在方法1中,对象将在函数返回时自动删除。
in method 1 the object will be automatically deleted when the function returns.
这篇关于这是在C ++中实例化对象的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!