【发布时间】:2019-11-20 11:20:37
【问题描述】:
我想通过移动std::vectors 的数据从两个std::vector 中创建std::vector 的std::tuple (std::vector<std::tuple<Ts...>>)。
假设我有一个与此类似的结构(添加 std::couts 以展示问题)。
template<typename T>
struct MyType
{
constexpr MyType() { std::cout << "default constructor\n"; }
constexpr MyType(const T& data) : m_data(data)
{
std::cout << "data constructor\n";
}
constexpr MyType(const MyType& other) : m_data(other.m_data)
{
std::cout << "copy constructor\n";
}
constexpr MyType(MyType&& other) noexcept : m_data(std::move(other.m_data))
{
std::cout << "move constructor\n";
}
~MyType() = default;
constexpr MyType& operator=(const MyType& other)
{
std::cout << "copy operator\n";
m_data = other.m_data;
return *this;
}
constexpr MyType& operator=(MyType&& other) noexcept
{
std::cout << "move operator\n";
m_data = std::move(other.m_data);
return *this;
}
private:
T m_data{};
};
现在我们可以为std::vector<MyType<T>>的右值引用定义一个operator+:
template<typename LhsT, typename RhsT>
constexpr auto operator+(std::vector<MyType<LhsT>>&& lhs, std::vector<MyType<RhsT>>&& rhs)
{
if(lhs.size() != rhs.size())
throw std::runtime_error("");
std::vector<std::tuple<MyType<LhsT>, MyType<RhsT>>> ret(lhs.size());
std::cout << "before transform\n";
std::transform(std::make_move_iterator(lhs.cbegin()),
std::make_move_iterator(lhs.cend()),
std::make_move_iterator(rhs.cbegin()),
ret.begin(),
[](auto&& lhs_val, auto&& rhs_val) {
return std::make_tuple(lhs_val, rhs_val);
});
std::cout << "after transform\n";
return ret;
}
现在我遇到了问题。运行此代码时
int main()
{
std::vector<MyType<int>> int_vec(1);
std::vector<MyType<float>> float_vec(1);
std::cout << "before move operator+\n";
auto int_float_tp_vec = std::move(int_vec) + std::move(float_vec);
std::cout << "after move operator+\n";
}
输出是这样的:
default constructor
default constructor
before move operator+
default constructor
default constructor
before transform
copy constructor
copy constructor
move operator
move operator
after transform
after move operator+
问题是:为什么会调用copy constructor?在这里使用std::make_tuple 是错误的方法吗?如果不调用copy constructor 或copy operator,我怎么能做到这一点?
LIVE DEMO
【问题讨论】:
-
从 const 移动一般是一个副本。
标签: c++ vector tuples c++17 move-semantics