PDA

View Full Version : How to use the STL from an ObjC++ class?


Rubel
2003.04.18, 09:39 PM
I would like to have a vector as an instance variable. Is there a way to do this safely? I'm trying to call the constructor manually from the init method, like this:
- (id) init { [super init]; Time.vector(); return self; }

but that generates this error:
TrackerKeeper.mm:6: calling type `std::vector<Work, std::allocator<Work> >' like a method

I would use a pointer, but it would become invalid as soon as I change the vector, right?

What's the best way to go about using the STL with ObjC++? Or should I just give up and use a NSMutableArray?

OneSadCookie
2003.04.19, 01:08 AM
If you really need to have a C++ object as a by-value field in an ObjC object, you need to use placement new to initialize it, and you need to call the destructor manually.

I've not done this myself, but something like:

#include <new>

-(id)init
{
self = [super init];
if (self == nil)
{
return nil;
}

new(&Time) vector<Work>();

return self;
}

- (void)dealloc
{
Time.~vector<Work>();
}

(Syntax may be slightly wrong or totally wrong, but I know the idea's solid :p )

Rubel
2003.04.20, 09:13 PM
That sounds a bit scary (I've seen all these warnings against using placement new), but if that's what it takes...

thanks for the info.