Let\'s assume I have a class with only one constructor:
class T {
public:
T(BigClass&& big) : big(std::move(big)) {}
...
SomeBigClass
};
It's not hard to write:
template <typename T>
T make_temp(const T& x) { return x; }
There might be a standard function that happens to do that by accident when called with one argument, but there isn't one designed for this unusual pattern.
Why can't you just copy the BigClass
object?
void foo(const BigClass& big) {
while (...) {
T t{ BigClass(big) };
...
}
}
This makes a temporary BigClass
that is then moved into the T
If you can manipulate T
you could template the constructor.
#include <iostream>
using namespace std;
class B
{
int x;
public:
B (int i) : x(i) { }
B (B && b) : x(b.x) { cout << "B moved (" << x << ")" << endl; }
B (B const & b) : x(b.x) { cout << "B copied (" << x << ")" << endl; }
};
class A
{
B b;
public:
template<typename TB>
A (TB && init_b) : b(std::forward<TB &&>(init_b)) { }
};
B foo (void) { B x(3); return x; }
int main (void)
{
A a1(foo());
B b1(4);
A a2(b1);
return 0;
}
Prints
B moved (3)
B copied (4)
As far as I understand reference collapsing you should come out with a constructor A(B&)
forwarding to the copy constructor of B
and a A(B&&)
forwarding to the move constructor of B
.