C++编译器如何合成默认的复制构造函数
由编译器合成的默认复制构造函数 没有定义自己的类会做正确的事情:它复制 所有成员从一个对象到另一个对象。
我想做类似的事情。我想写一个方法
template <typename T>
T f(const T& obj) {
// for each member var i of obj, I want to call some method g(obj.i)
}
现在我不知道成员变量的名称是什么。如果这是 复制构造函数,我可以调用赋值运算符而不是 g。
显然编译器会这样做(但也许它是在推断出之后才这样做的) 班级成员的姓名)。是否可以这样做 对于任何 T 类?
The default copy constructor that is synthesized by the compiler for
a class that does not define its own does the right thing: it copies
all the members from one object to another.
I want to do something similar. I want to write a method
template <typename T>
T f(const T& obj) {
// for each member var i of obj, I want to call some method g(obj.i)
}
Now I don't know what the names of the member variables are. If this was
the copy constructor, I could call the assignment operator instead of g.
Clearly the compiler does this (but maybe it does this after it has inferred
the name of the members of the class). Is it even possible to do this
for any class T ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
编译器有一些代表每个类的内部数据结构。当谈到合成复制构造函数时,它可以参考这个结构来找出它需要发出什么代码(有多少个副本,每个副本是如何完成的,以及成员的地址与源的关系是什么)和目标对象地址)。
作为一名纯粹的 C++ 程序员,您无权访问此内部编译时数据结构,因此您非常不走运。你基本上必须列出成员并希望不要遗漏任何成员。
您也许可以使用预处理器(或者如果不是the预处理器,则a预处理器),用额外的信息来注释您的结构定义,您可以使用这些信息来生成以下列表:每位成员一次通话。
The compiler has some internal data structure representing each class. When it comes to synthesize the copy constructor, it can refer to this structure in order to figure out what code it needs to emit (how many copies, how each one is done, and what the addresses of the members are in relation to the source and destination object addresses).
As a mere C++ programmer, you don't have access to this internal compile-time data structure, so you're pretty much out of luck. You basically have to list the members and hope you don't leave any out.
You could perhaps do work with the preprocessor (or if not the preprocessor then a preprocessor), to annotate your struct definition with extra information that you can use to generate the list of one call for each member.
不,你不能这样做。 C++ 没有方法反射,尽管您可以通过在像Qt这样的框架。 (顺便说一句,这是一个很棒的框架,我一直在使用它,它只在 C++ 之上提供了薄如纸的一层。)编译器也不需要这样做——也就是说,它不需要推断成员的姓名。它只知道对象地址的内存偏移量和每个成员的类型,并通过调用其构造函数将它们复制到目标对象。
No, you can't do this. C++ doesn't have method reflection, though you can do this by working within a framework like Qt. (Which btw is a great framework, I use it all the time and it provides only a paper-thin layer on top of C++.) The compiler doesn't need to do this either--that is, it doesn't need to infer names of members. It just knows the memory offset from the address of the object and the type of each member, and copies those to the target object by calling their constructors.