大家好,我在创建的可变参数添加模板上没有调用 move ctor 的问题。
#include <iostream>
#include <algorithm>
#include <functional>
class wrapped_heap_integer{
public:
wrapped_heap_integer() : value(nullptr)
{
std::cout << "Default ctor\n";
}
explicit wrapped_heap_integer(int value_) : value(new int(value_))
{
std::cout << "ctor\n";
}
~wrapped_heap_integer(){
if(value != nullptr) delete value;
std::cout << "dtor\n";
}
wrapped_heap_integer(wrapped_heap_integer const & other) : value(new int(*(other.value))){
std::cout << "copy ctor\n";
}
wrapped_heap_integer(wrapped_heap_integer&& other) : value(other.value){
other.value = nullptr;
std::cout << "move ctor\n";
}
wrapped_heap_integer& operator = (wrapped_heap_integer other){
std::swap(value,other.value);
std::cout << "copy assignment\n";
return *this;
}
wrapped_heap_integer& operator = (wrapped_heap_integer&& other){
delete value;
value = other.value;
other.value = nullptr;
std::cout << "move assignment\n";
return *this;
}
wrapped_heap_integer operator + (wrapped_heap_integer const & other){
wrapped_heap_integer a(*value + *(other.value));
return a;
}
wrapped_heap_integer& operator+=(wrapped_heap_integer const & other){
*value += *(other.value);
return *this;
}
friend std::ostream& operator << (std::ostream& o, wrapped_heap_integer& w);
private:
int* value;
};
std::ostream& operator << (std::ostream& o, wrapped_heap_integer& w){
o << *(w.value);
return o;
}
template<typename Head>
Head&& add(Head&& head){
return std::forward<Head>(head);
}
template<typename Head, typename... Tail>
auto add(Head&& head, Tail&&... tail) -> decltype(head + add(std::forward<Tail>(tail)...))
{
return head + add(std::forward<Tail>(tail)...);
}
int main(int argc, const char * argv[])
{
auto result = add(wrapped_heap_integer(4),wrapped_heap_integer(10),wrapped_heap_integer(1));
std::cout << result << std::endl;
return 0;
}