简体   繁体   English

C++:实例化 header 文件中声明的 object

[英]C++: instantiating object that is declared in a header file

If an object is declared in a header file like this:如果 object 在 header 文件中声明,如下所示:

Object obj;

What would be the best way to instantiate it?实例化它的最佳方法是什么? A simple reassignment like this?像这样简单的重新分配? Does this destroy the declared object and create a new one and can this lead to errors?这会破坏声明的 object 并创建一个新的,这会导致错误吗?

obj = Object(...);

Or should I use a pointer and create the object with new?或者我应该使用指针并使用新创建 object? This way i can be sure that only here the object gets created.这样我可以确定只有在这里 object 被创建。

obj = new Object(...);

Or should the class have a init method, so the object does not get destroyed and recreated?还是应该 class 有一个 init 方法,所以 object 不会被破坏和重新创建?

Would you do it any different if the object is a member of a class?如果 object 是 class 的成员,你会有什么不同吗?

Object obj;

already instantiates the object.已经实例化了 object。 SO you really should not have it in a header file所以你真的不应该把它放在 header 文件中

you probably want你可能想要

Object *obj;

ie a pointer to an object, then instantiate with 'new'.即指向 object 的指针,然后用“new”实例化。

But better would be std::unique_ptr<Object>但更好的是std::unique_ptr<Object>

Don't instantiate objects in a header file.不要在 header 文件中实例化对象。 If you include that header file in multiple translation units, you will get linker errors about duplicate ojects.如果您在多个翻译单元中包含该 header 文件,您将收到有关重复项目的 linker 错误。

If you want to share an object with multiple units, use extern .如果您想与多个单元共享 object,请使用extern

In the header:在 header 中:

extern Object obj;

In a cpp file:在一个 cpp 文件中:

Object obj(...);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM