我的問題是在下面,以避免在載體複製多個副本。避免在向量中的多個拷貝在C++
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
class DataValue {
public:
DataValue() { std::cout << "DataValue constructor called" << std::endl; }
DataValue(DataValue const& other) { cout << "DataValue copy constructor called" << std::endl; }
~DataValue() { std::cout << "DataValue destructor is called" << std::endl; }
private:
};
class ItemDataHistory {
public:
ItemDataHistory() { std::cout << "ItemDataHistory constructor called" << std::endl; }
// ItemDataHistory(ItemDataHistory const & other) { std::cout << "ItemDataHistory copy constructor called" << std::endl; }
~ItemDataHistory() { std::cout << "ItemDataHistory destructor called" << std::endl; }
std::vector<DataValue>& GetVecDataValues() { return m_vecDataValues; }
private:
std::vector<DataValue> m_vecDataValues;
};
class DataReply {
public:
DataReply() { std::cout << "Data reply constructor is called "<< std::endl; }
~DataReply() { std::cout << "Data reply destructor is called "<< std::endl; }
DataReply(const DataReply&) { std::cout << "Data reply copy constructor is called "<< std::endl; }
std::vector<ItemDataHistory>& GetItemDataHistories() { return m_vecItemData; }
private:
// The list of DataValue
std::vector<ItemDataHistory> m_vecItemData;
};
void main()
{
DataValue dv1, dv2, dv3;
ItemDataHistory itmDH;
itmDH.GetVecDataValues().reserve(3);
itmDH.GetVecDataValues().push_back(dv1);
itmDH.GetVecDataValues().push_back(dv2);
itmDH.GetVecDataValues().push_back(dv3);
DataReply dr;
dr.GetItemDataHistories().reserve(1);
dr.GetItemDataHistories().push_back(itmDH); // Here copy consturtor of itemdatahistory is called and all data values are copied.
// Here I want to avoid data values constructor to be called again how can I avoid this
// How can I directly insert values of dv1, dv2, dv3 into "dr" with out using "itmDH"?
return;
}
請注意,我不能在上面的std :: vector m_vecItemData中使用指針;在數據回覆類,因爲這些接口類從libary並沒有關於它的控制和我打電話功能,因此而在範圍數據
我的問題是,在上面的代碼註釋給出的功能可以使用的數據。原因是我有數千個數據值。爲了避免數據值被稱爲多重構造,我想(用itmDH局部變量即與出)
和其他問題被
我如何可以保留數據的空間插入數據值直接將數據回覆數據回覆中的值?
你是什麼意思ItemDataHistory做活動?和其他問題是,如果itmDH超出範圍將博士仍然包含有效的數據值。謝謝! – venkysmarty 2013-03-08 06:19:42
谷歌「移動語義C++」,這是一個有點多的Q /如此的格式。並且,只要您將'itmDH'複製或移動到其中,'dr'將包含有效值。 – 2013-03-08 06:23:18