【发布时间】:2013-11-27 23:20:35
【问题描述】:
以下安全吗?第一个类成员初始化后std::string 不是moved 吗?打印出来没问题,但我不确定。
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");
}
我想这没关系,因为 C 的第三个 ctor 参数是 const std::string&,但是我如何防止在采用 r 值 ref 的类中完美转发,例如C(int, int, std::string&&) as then m_two 将不会收到与 m_one 相同的 ctor args?
将 Test 的 ctor 更改为
template <typename... Args>
Test(Args&... args)
不编译。也不会从 m_one 和 m_two ctors 中删除 std::forward<Args>(args)...。
【问题讨论】:
-
初始化
m_one的时候最好不要使用std::forward。 -
无法编译:main.cpp:31: 错误:无法将 'std::basic_string
' 左值绑定到 'std::string&& {aka std::basic_string && }' -
@James:你一定做错了什么。沃恩的意思是this。经验法则是:当多次完美转发同一个参数时,不要。无需完美转发,只需将其传递,并让目标制作副本(如果他们愿意)。如果你想转发,只在最后一次(在这种情况下
m_two的初始化)。 -
@Xeo,是的,你是对的
标签: c++ templates c++11 perfect-forwarding