[英]Forward variadic template args to several class members
以下是安全的嗎? 初始化第一個類成員后, 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");
}
我想這沒關系,因為C
的第三個ctor參數是const std::string&
,但是如何在一個帶有r值ref的類中阻止完美轉發,例如C(int, int, std::string&&)
m_two
不會收到與m_one
相同的ctor args?
將測試的ctor更改為
template <typename... Args>
Test(Args&... args)
不編譯。 也沒有從m_one
和m_two
中刪除std::forward<Args>(args)...
你會想要使用這樣的東西:
#include <memory>
#include <string>
#include <iostream>
#include <utility>
template <typename T>
class Test
{
public:
template <typename... Args>
Test(Args&&... args)
: m_one(new T(args...)), // avoid moving the first time
m_two(new T(std::forward<Args>(args)...)) // but allowing moving the last time
{
}
private:
std::unique_ptr<T> m_one;
std::unique_ptr<T> m_two;
};
class C
{
public:
C(int a, int b, std::string c) // rule of thumb -- if you are going to copy an argument
// anyway, pass it by value.
: m_a(a),
m_b(b),
m_c(std::move(c)) // you can safely move here since it is the last use.
{
std::cout << "ctor a=" << m_a << ", b=" << m_b << ", c=" << m_c << "\n";
}
int m_a;
int m_b;
std::string m_c;
};
對於m_one
,參數使用左值引用,因此不會發生移動。 對於m_two
, std::forward
將根據需要使用rvalue引用。 將std::string
參數取值為C
並使用std::move
使其適用於任何一種情況。 如果傳遞左值引用,則參數將被復制構造,但是如果傳遞右值引用,則參數將被移動構造。 在任何一種情況下,您都可以將參數移動到m_c
成員中以提高效率。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.