大家都知道我没有在我创建的可变参数添加模板上调用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;
}
答案 0 :(得分:0)
我认为你在这里得到了普遍的参考。将参数转发为不复制右值。
template<typename Head>
Head add(Head&& head){
return std::forward<Head>(head);
}