LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   stl vector as a member of a struct (https://www.linuxquestions.org/questions/programming-9/stl-vector-as-a-member-of-a-struct-856863/)

elias_28 01-17-2011 12:55 PM

stl vector as a member of a struct
 
Hi,

is there any problem that might rise by by having a vector as a member of struct in c++ as follows.

ex.

struct A
{
int a;
vector<int> b;
}

class B {
A **ptr_A;
}

i am having a double pointer to A and allocating the data to that ptr with malloc. I know that i am mixing C with C++ but i want to know if there can be any memory problems predicted by having this mixture.

Especially that the constructor of b will not be called when allocating A.

thanks

johnsfine 01-17-2011 01:05 PM

Quote:

Originally Posted by elias_28 (Post 4227704)
is there any problem that might rise by by having a vector as a member of struct in c++

Normally no. But ...

Quote:

i am having a double pointer to A and allocating the data to that ptr with malloc. I know that i am mixing C with C++ but i want to know if there can be any memory problems predicted by having this mixture.

Especially that the constructor of b will not be called when allocating A.
I'm not clear on what you are allocating with malloc (even less clear on why).

The constructor/destructor that matters in the code you posted is A() and ~A(). You need to be sure those are called correctly.

For example (but I didn't test it for typos etc.):
Code:

B b;
b.ptr_A = (A**)( malloc( n * sizeof(A*) ) );

I think that is OK, because the pointers don't necessarily need construction.

Code:

b.ptr_A[0] = (A*)(malloc( sizeof(A) ) );
That one is not OK. It is skipping the constructor for A.

But regarding your question about problems arising from having a vector as a member of a struct: I think that is a very distorted point of view. The problem (if any) comes from not calling a required constructor. Blaming that problem on the aspect of the struct that requires construction is not a good software engineering viewpoint.

XavierP 01-17-2011 02:38 PM

Moved: This thread is more suitable in Programming and has been moved accordingly to help your thread/question get the exposure it deserves.


All times are GMT -5. The time now is 04:59 AM.