Bult-in array of objects

X

X.

Hi,

There's been a discussion here on a similar topic that I'd like to
push a step further.
Suppose I get a class S having constructors:
S(int n) - allocates n bytes of memory
S() - allocates nothing
and a copy constructor,copy assigment op. and so on.

I intend to declare a table of structures that contain (among other
things)objects of S with some memory allocated. When I simple-minded
code something like this:
struct {
S field1(20); //error here
...
} x[100];

then my compiler insists to use default constructor which doesn't
allocate anything. And all my attempts to apply some object oriented
programming like:
class X {
S field1;
...
X(int n): field1(n) {}
};

X x[100];
for(i...)
{ X xxx(20); //to get space for xxx
x = xxx; //hope the memory chunk will be assigned to x
}
fall short because the operator= doesn't allocate memory, and flags an
error. In other words, it can't copy an object to an "empty" one).

Well, I could use vector<> or another container (or even overload
operators of S yet I'd prefer not doing so) but this thought's
torturing me in this New Year Eve: how to use a built-in tables to
keep objects? Books (ex.Lippmann's one) claim that's possible but give
no hints.

Happy New Year to those who will reply to my post and those who won't.
X.
 
J

Jonathan Mcdougall

X. said:
Hi,

There's been a discussion here on a similar topic that I'd like to
push a step further.
Suppose I get a class S having constructors:
S(int n) - allocates n bytes of memory
S() - allocates nothing
and a copy constructor,copy assigment op. and so on.

I intend to declare a table of structures that contain (among other
things)objects of S with some memory allocated. When I simple-minded
code something like this:

Arrays can only be default-constructed. Either
use standard containers (or roll you own) or use
an array of pointers.


Jonathan
 
J

Jeff Flinn

X. said:
Hi,
....

Well, I could use vector<> or another container (or even overload
operators of S yet I'd prefer not doing so) but this thought's
torturing me in this New Year Eve: how to use a built-in tables to
keep objects? Books (ex.Lippmann's one) claim that's possible but give
no hints.

See boost.array and boost.assignment libraries at www.boost.org.

Happy New Year to those who will reply to my post and those who won't.

Ditto.

Jeff
 
A

adbarnet

With a glass or two of New Year's fortitude already down, I'd say this looks
like a job for placement new.

Shoot me where I sit if that's completely off the mark. I'll die happy.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,196
Messages
2,571,036
Members
47,631
Latest member
kukuh

Latest Threads

Top