作为对象的类成员 - 指针与否? C ++ [英] Class members that are objects - Pointers or not? C++

查看:184
本文介绍了作为对象的类成员 - 指针与否? C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我创建一个类MyClass,它有一些私人成员说MyOtherClass,是更好的让MyOtherClass一个指针或不是?它是什么意思,还有它不是一个指针在它在内存中的存储方面?



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

$ b


>

如果我创建了一个类MyClass,并且它有一个私人成员说MyOtherClass,是不是更好地让MyOtherClass成为一个指针?


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


它是什么意思,还有它不是一个指针在存储在内存中的位置?


其地址将接近(或等于) - gcc(例如)有一些高级选项转储类数据(大小,vtable,偏移量)


创建类时是否创建对象?


是 - 如果编译器重新对齐,MyClass的大小将增加sizeof(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?

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

Regards

Mark

解决方案

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?

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?

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

这篇关于作为对象的类成员 - 指针与否? C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆