C++17中有一种方法。在 C++11/14 中不起作用,因为在 C++17 中强制要求 RVO。
需要中级课程C
用于构造A
。在 C++17 的早期版本中,您必须添加一个额外的构造函数A
.
#include <tuple>
#include <iostream>
#include <utility>
struct A {
int& x;
int& y;
A(int& a, int& b) : x(a), y(b) {}
A(const A&) = delete;
A& operator=(const A&) = delete;
};
struct C {
int* x;
int* y;
C(int& a, int& b) : x(&a), y(&b) {};
operator A () const
{
return A(*x,*y);
}
};
class B {
public:
B(int& w, int& x, int& y, int& z)
: a_b_{ C{w,x}, C{y,z}} {}
private:
std::tuple<A, A> a_b_;
};
int main() {
int w =1, x=2, y=3, z=4;
B b{w,x,y,z};
return 0;
}
如果你要使用std::pair
代替std::tuple
,你也可以通过以下方式实现它std::piecewise_construct
. See,
#include <tuple>
#include <iostream>
#include <utility>
struct A {
int& x;
int& y;
A(int& a, int& b) : x(a), y(b) {}
A(const A&) = delete;
A& operator=(const A&) = delete;
};
class B {
private:
std::pair<A, A> a_b_;
public:
B(int& w, int& x, int& y, int& z)
: a_b_{std::piecewise_construct, std::forward_as_tuple(w,x), std::forward_as_tuple(y,z)} {}
};
int main() {
int w =1, x=2, y=3, z=4;
B b{w,x,y,z};
return 0;
}