问题描述
自从我第一次看到它的前进方向以来,我一直感到怀疑,但是现在我看了一些我的代码(中等水平的初学者),它不仅使我感到丑陋,而且可能会很慢?
I had my doubts since I first saw where it leads, but now that I look at some code I have (medium-ish beginner), it strikes me as not only ugly, but potentially slow?
如果我在class A
内有一个struct S
,并用class B
(组成)调用,则我需要执行以下操作:
If I have a struct S
inside a class A
, called with class B
(composition), and I need to do something like this:
struct S { int x[3] {1, 2, 3}; };
S *s;
A(): s {new S} {}
B(A *a) { a->s->x[1] = 4; }
该链:a->s->x[1]
的效率如何?这是丑陋且不必要的吗?潜在的阻力?如果链中还有更多的级别,那么丑吗?应该避免这种情况吗?或者,如果碰巧没有以前的机会,这是比以下更好的方法:
How efficient is this chain: a->s->x[1]
? Is this ugly and unnecessary? A potential drag? If there are even more levels in the chain, is it that much uglier? Should this be avoided? Or, if by any chance none of the previous, is it a better approach than:
S s;
B(A *a): { a->s.x[1] = 4; }
它看起来像这样慢了,因为(如果我理解正确的话)我必须制作struct
的副本,而不是使用指向它的指针.我不知道该怎么想.
It seems slower like this, since (if I got it right) I have to make a copy of the struct
, rather than working with a pointer to it. I have no idea what to think about this.
推荐答案
如果您只是不显示,则完全不显示.
In the case you just showed no, not at all.
首先,在现代C ++中,应避免拥有所有权的原始指针,这意味着永远不要使用new
.使用适合您需要的智能指针之一:
First of all, in modern C++ you should avoid raw pointers with ownership which means that you shouldn't use new
, never. Use one of the smart pointers that fit your needs:
-
std::unique_ptr
拥有唯一所有权. -
std::shared_ptr
用于多个对象->相同资源.
std::unique_ptr
for sole ownership.std::shared_ptr
for multiple objects -> same resource.
我无法确切地告诉您性能,但是通过成员s
进行的直接访问永远不会比通过取消引用的成员s
进行的直接访问慢.您应始终在此处使用非指针方式.
I can't exactly tell you about the performance but direct access through the member s
won't ever be slower than direct access through the member s
that is dereferenced. You should always go for the non-pointer way here.
但请再退一步.首先,您甚至不需要在这里使用指针. s
应该只是第二个示例中的对象,并替换B
的构造函数中的指针作为参考.
But take another step back. You don't even need pointers here in the first place. s
should just be an object like in your 2nd example and replace the pointer in B
's constructor for a reference.
不,不会复制.
这篇关于通过链->-指针访问变量的效率如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!