iwat0qs
iwat0qs

Reputation: 156

Can I simply call a constructor on allocated memory, instead of placement new?

So I have a container-like pool class, which is basically a wrapper to an std::vector<char*> blocks, where memory is allocated by doing:

char* block = new char[elementSize * blockSize];
blocks.push_back( block );

This pool has a void* get_addr( std::size_t n ) which returns the memory address of element n.

I know, that I can construct a new object there by doing: new( get_addr(n) ) Object( args ); But I can also do it this way:

// Create a supplimentary method
T& get( std::size_t n ) { return *static_cast<T*>( get_addr(n) ); }
// ... 
// ...
// and an example usage, where Object is arbitrary
Object& obj = pool.get( 10 );
obj = Object( args );

I've tried both, and of course the placement new method works, but so does the second method of constructing too. And so I'm interested, in whether are there any restrictions on why I shouldn't use the second way, or is it safe to do so.

Upvotes: 1

Views: 332

Answers (1)

Puppy
Puppy

Reputation: 146910

It's completely unsafe to do so, as you are assigning to an object which is uninitialized. This will break pretty much any complex type.

Placement new is literally calling the constructor on allocated memory - that's it's job and purpose. The question you're asking simply doesn't make sense. "How can I use language feature X without using X?". You must construct objects before doing shit with them.

Upvotes: 6

Related Questions