以下安全吗?第一个类成员初始化后不会std::string
被调用吗?move
打印出来没问题,但我不确定。
template <typename T>
class Test
{
public:
template <typename... Args>
Test(Args&&... args)
: m_one(new T(std::forward<Args>(args)...)),
m_two(new T(std::forward<Args>(args)...)) // <- Here
{
}
private:
std::unique_ptr<T> m_one;
std::unique_ptr<T> m_two;
};
class C
{
public:
C(int a, int b, const std::string& c)
: m_a(a),
m_b(b),
m_c(c)
{
std::cout << "ctor a=" << m_a << ", b=" << m_b << ", c=" << m_c << "\n";
}
int m_a;
int m_b;
std::string m_c;
};
int main()
{
Test<C> t(1, 2, "3");
}
我想这没关系,因为 is 的第三个 ctor 参数C
,const std::string&
但是我如何防止在一个采用 r 值 ref 的类中完美转发,例如C(int, int, std::string&&)
,因为 thenm_two
不会收到与 相同的 ctor args m_one
?
将 Test 的 ctor 更改为
template <typename... Args>
Test(Args&... args)
不编译。也不会删除std::forward<Args>(args)...
fromm_one
和m_two
ctors。