C ++在向量中的好奇行为:: push_back() [英] C++ curious behavior in vector::push_back()
问题描述
我有一个名为Task的类的数据结构:
I have the following data-structure as a class named "Task":
private:
string name;
int computation_time;
int period;
此外,我有一个ASCII文件与此内容:
Furthermore i have a ASCII-File with this content:
A 3 10
B 2 12
C 1 11
name = A,computation_time = 3,period = 10 and so on ....
name = A, computation_time = 3, period = 10 and so on....
现在我想读文件,创建Task对象并将其推回到向量中:
Now i want to read in the file, create Task-object and push it back into a vector:
void read_in_task_list_and_create_tasks(const string &filename, vector<Task> ¤t_tasks)
{
ifstream in_file;
in_file.open(filename.c_str());
string tmp_name;
int tmp_computation_time;
int tmp_period;
while(!in_file.eof())
{
in_file >> tmp_name;
in_file >> tmp_computation_time;
in_file >> tmp_period;
// Task tmp_task(tmp_name, tmp_computation_time, tmp_period);
// current_tasks.push_back(tmp_task);
current_tasks.push_back(Task(tmp_name, tmp_computation_time, tmp_period));
}
}
现在,当我查看current_tasks向量时,它有元素,但它们的值不匹配我的in_file值。
观看取消注释的行。
Now, when i take a look into current_tasks vector, it has elements, but their values dont match my in_file values. Watch the outcommented lines. tmp_task object is exactly correct, but if it's getting pushed back, it loses it's values like descriped above.
这可能是Task-Class中的一个复制 - 构造函数,因为它是一个复制 - 构造函数std :: vector正在管理内存分配?
Could this be a Copy-Constructor Issue in Task-class, because std::vector is managing the memory-allocation?
我在Linux x86上使用带有g ++编译器的netbeans。
I'm using netbeans with g++ compiler on Linux x86.
THX
推荐答案
确保没有定义复制构造函数或赋值运算符。
Make sure there are no copy constructors or assignment operators defined.
自动的应该做你想要的。
The automatic ones should do exactly what you want.
这篇关于C ++在向量中的好奇行为:: push_back()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!