在构造函数初始化中重用临时对象
在类的构造函数中初始化类的成员时,如何在多个点使用同一个临时变量?
示例:
// for arbitrary T1, T2, T3
T2 foo(T1 const&);
T3 bar(T1 const&);
struct A {
T2 const t2;
T3 const t3;
A() : t2(foo(T1())), t3(bar(T1())) {}
};
这是一个非常简化的示例,但 t2
和 t3
都是根据 T1
的实例构造的。现在,如果我希望该对象在两次初始化中完全相同*,我就会遇到问题,因为它没有名称。您知道如何在不使用 C++11 构造函数调用构造函数功能也不添加调用 A(T1() 的虚拟类的情况下解决此问题吗? )?
*像这样:
A(T1 const& t1) : t2(foo(t1)), t3(bar(t1)) {}
动机:如果 T1()
实际上是类似于 new T()
的东西,其中对象的地址很重要,那么我必须谈论t2
和 t3
中的对象相同。
When initialising members of a class in its constructor, how can you use the same temporary at more than one point?
Example:
// for arbitrary T1, T2, T3
T2 foo(T1 const&);
T3 bar(T1 const&);
struct A {
T2 const t2;
T3 const t3;
A() : t2(foo(T1())), t3(bar(T1())) {}
};
This is a very simplified example, but both t2
and t3
are constructed depending on an instance of T1
. Now If I want that object to be precisely the same in both initialisations* I have a problem, because it has no name. Do you have an idea how to solve this without the C++11 constructor-calls-constructor feature nor adding a dummy class that calls A(T1())
?
*like so:
A(T1 const& t1) : t2(foo(t1)), t3(bar(t1)) {}
Motivation: What if T1()
is actually something like new T()
, where the address of the object matters, such that I have to talk about the same object in both t2
and t3
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在构造函数初始化中重用临时参数的一种肮脏方法是添加虚拟参数。我并不热衷于这种技术,但我知道这是唯一给临时命名的技术。我倾向于重新设计我的课程来避免这种情况。
A dirty way to reuse a temporary in the constructor initialization is to add a dummy parameter. I'm not keen on this technique, but is the only one I know to give the temporary a name. I tend to redesign my classes to avoid this.
最近,常量引用可能默认为临时的(我忘记这是 C++03 还是 C++11 的补充):(
也许声明该构造函数
显式
,以防万一。)Const-references may be defaulted to a temporary, as of recently (I forget whether that's a C++03 or C++11 addition):
(Maybe declare that constructor
explicit
, just in case.)我会通过创建工厂方法来解决这个问题
I'd solve this by creating a factory method
我会不惜一切代价避免这种情况,但如果我不得不,我会添加一个额外的成员:
I'd avoid this situation at all costs, but if I had to, I'd add an extra member: