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

Class members that are objects - Pointers or not? C++(作为对象的类成员 - 指针与否?C++)
本文介绍了作为对象的类成员 - 指针与否?C++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

如果我创建一个类 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)

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

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

OpenGL transforming objects with multiple rotations of Different axis(OpenGL 变换不同轴多次旋转的对象)
GLFW first responder error(GLFW 第一响应者错误)
SOIL not linking correctly(SOIL 连接不正确)
Core profile vs version string? Only getting GLSL 1.3/OGL 3.0 in mesa 10.0.1(核心配置文件与版本字符串?在 mesa 10.0.1 中只获得 GLSL 1.3/OGL 3.0)
What is the range of OpenGL texture ID?(OpenGL 纹理 ID 的范围是多少?)
How taxing are OpenGL glDrawElements() calls compared to basic logic code?(与基本逻辑代码相比,OpenGL glDrawElements() 调用的繁重程度如何?)