Louis
Louis

Reputation: 4210

C++ Add Object to Array

I need to instansiate an object and add it to an array. This is what I currently have in a method:

Row r;
rows[count] = r;

The problem here is r is on the stack and being removed after the function exits. I quick fix is to make r static but that is bad right? What should I do? (Sorry, complete C++ noob).

Edit: Removing the deconstructor for Row fixes the problem.

Upvotes: 0

Views: 4935

Answers (3)

Steve Jessop
Steve Jessop

Reputation: 279445

The line rows[count] = r copies the object r to the element at index count in the array. After that, it doesn't matter what happens to r, the array is unaffected.

[Edit: OK, it matters indirectly what happens to r - since the copy is using something that r can delete.]

This is surprising if you're used to (for example) Java, where an array element isn't actually an object, it's just a reference to one.

Upvotes: 7

Steve Townsend
Steve Townsend

Reputation: 54178

Use std::vector instead of the array, provided construction of Row is not arduous:

std::vector<Row> rows;

Row r;
rows.push_back(r);

When the vector goes out of scope, the destructor ~Row() will be called for each entry.

You can access the most recent added entry using either

const Row& last = rows.back();

or

size_t count = rows.size();
const Row& last = rows[count - 1];

Upvotes: 3

jkerian
jkerian

Reputation: 17056

In this case, you're actually creating it on the stack, and then copying the object to the location rows[count]. Note that if you created rows as an array of Row objects, there already was a Row object at that location, created with the default constructor, that you copied over.

For various reasons, in C++ we try to use the standard library containers like std::vector and std::list. These will expand to handle the new elements you add.

Upvotes: 0

Related Questions