我试图将文字传递给完美的转发设置器,但这会导致对象构造,移动和破坏。我正在寻找一种更有效的方法。
struct TStruct {
TStruct(int va) : a(va) {
std::cout << "- TStruct(" << va << ")" << std::endl;
}
TStruct(const TStruct& other) :
a(other.a)
{
std::cout << "- TStruct(const TStruct& )" << std::endl;
}
TStruct(TStruct&& other) :
a(std::exchange(other.a, 0))
{
std::cout << "- TStruct(const TStruct&&)" << std::endl;
}
TStruct& operator=(const TStruct& rhs) {
std::cout << "- TStruct operator= const& " << std::endl;
// check for self-assignment
if(&rhs == this) return *this;
a = rhs.a;
return *this;
}
TStruct& operator=(TStruct&& rhs) {
std::cout << "- TStruct operator=&&" << std::endl;
// check for self-assignment
if(&rhs == this) return *this;
a = std::exchange(rhs.a, 0);
return *this;
}
~TStruct() {
std::cout << "~ TStruct() destructor with " << a << std::endl;
}
int a = 1;
};
struct TPerfectForward {
template<class T>
TPerfectForward(T&& tsv) : ts(std::forward<T>(tsv)) {}
template<class T>
void set(T&& tsv) { ts = std::forward<T>(tsv); }
TStruct ts;
};
std::cout << "TPerfectForward (5)" << std::endl;
TPerfectForward pf(5);
std::cout << "TPerfectForward set(4)" << std::endl;
pf.set(4);
在Ubuntu上使用gcc 7.4.0可获得以下结果:
TPerfectForward (5);
- TStruct(5)
TPerfectForward set(4)
- TStruct(4)
- TStruct operator=&&
~ TStruct() destructor with 0
我希望这些结果更好:
TPerfectForward (5)
- TStruct(5)
TPerfectForward set(4)
- TStruct(4)
当完美转发到函数时,是否有一种方法可以避免调用move运算符和析构函数?