作为对象的类成员 - 指针与否?C++

2021-12-21 00:00:00 memory pointers class-design c++ member

如果我创建一个类 MyClass 并且它有一些私有成员 MyOtherClass,那么将 MyOtherClass 设为指针是否更好?就它在内存中的存储位置而言,让它不是指针又意味着什么?创建类时会创建对象吗?

If I create a class MyClass and it has some private member say MyOtherClass, is it better to make MyOtherClass a pointer or not? What does it mean also to have it as not a pointer in terms of where it is stored in memory? Will the object be created when the class is created?

我注意到 QT 中的示例通常在类成员是类时将类成员声明为指针.

I noticed that the examples in QT usually declare class members as pointers when they are classes.

推荐答案

如果我创建了一个类 MyClass 并且它有一些私有成员 MyOtherClass,那么将 MyOtherClass 设为指针是否更好?

If I create a class MyClass and it has some private member say MyOtherClass, is it better to make MyOtherClass a pointer or not?

你通常应该在你的类中将它声明为一个值.它将是本地的,出错的机会更少,分配更少――最终可能出错的事情更少,并且编译器总是可以知道它在指定的偏移量处,所以......它有助于优化和二进制减少几个级别.在某些情况下,您知道必须处理指针(即多态、共享、需要重新分配),通常最好仅在必要时使用指针 - 特别是当它是私有/封装的时.

you should generally declare it as a value in your class. it will be local, there will be less chance for errors, fewer allocations -- ultimately fewer things that could go wrong, and the compiler can always know it is there at a specified offset so... it helps optimization and binary reduction at a few levels. there will be a few cases where you know you'll have to deal with pointer (i.e. polymorphic, shared, requires reallocation), it is typically best to use a pointer only when necessary - especially when it is private/encapsulated.

就它在内存中的存储位置而言,让它不是指针意味着什么?

What does it mean also to have it as not a pointer in terms of where it is stored in memory?

它的地址将接近(或等于)this -- gcc(例如)有一些高级选项来转储类数据(大小、vtables、偏移量)

its address will be close to (or equal to) this -- gcc (for example) has some advanced options to dump class data (sizes, vtables, offsets)

创建类时会创建对象吗?

Will the object be created when the class is created?

是的 - MyClass 的大小将增加 sizeof(MyOtherClass),或者更多,如果编译器重新对齐它(例如到它的自然对齐)

yes - the size of MyClass will grow by sizeof(MyOtherClass), or more if the compiler realigns it (e.g. to its natural alignment)

相关文章