bitmask
bitmask

Reputation: 34628

Reuse of temporary in constructor initialisations

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.

Upvotes: 0

Views: 115

Answers (4)

Robᵩ
Robᵩ

Reputation: 168616

I'd avoid this situation at all costs, but if I had to, I'd add an extra member:

struct A {
  T1 temp_;
  T2 const t2;
  T3 const t3;
  A() : temp_(), t2(foo(temp_)), t3(bar(temp_)) {}
};

Upvotes: 0

Kerrek SB
Kerrek SB

Reputation: 476990

Const-references may be defaulted to a temporary, as of recently (I forget whether that's a C++03 or C++11 addition):

A::A(const T & t = T()) : a(t), b(t) { }
//              ^^^^^^

(Maybe declare that constructor explicit, just in case.)

Upvotes: 3

sehe
sehe

Reputation: 392911

I'd solve this by creating a factory method

// for arbitrary T1, T2, T3
T2 foo(T1 const&);
T3 bar(T1 const&);

struct A {
    T2 const t2;
    T3 const t3;
    static A createA() { return A(T1()); }

  private:
     A(const T1& t) : t2(foo(t)), t3(bar(t)) {}
};

Upvotes: 0

K-ballo
K-ballo

Reputation: 81349

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.

struct A
{
    A( T1 temporary_ = T1() )
      : t2( foo( temporary_ ) )
      , t3( bar( temporary_ ) )

    T2 const t2;
    T3 const t3;
};

Upvotes: 4

Related Questions