Community
cancel
Showing results for 
Search instead for 
Did you mean: 
Highlighted
New Contributor I
6 Views

Scalable allocator vs virtual methods - a bug ?

Jump to solution
Hello,

I just started playing with memory allocators - up to now I only used new/delete.
And possibly I observeda bug - the following code crashes on my box (for both scalable and cache aligned allocators):

#include

#include "tbb/scalable_allocator.h"
#include "tbb/cache_aligned_allocator.h"

struct sth {
double x;
int i;

sth (double ax, int ai) : x(ax), i(ai) {};

virtual void show (void) {
std::cout << "x = " << x << std::endl;
std::cout << "i = " << i << std::endl;
};
};

tbb::scalable_allocator alloc;
//tbb::cache_aligned_allocator alloc;

int main () {
sth *ex = alloc.allocate (1);
ex->x = 3.1415926;
ex->i = 13;
ex->show ();
alloc.deallocate (ex, 1);
return 0;
}

As a matter of fact, switching the method to be non-virtual makes the program work correctly.
Is it a bug ? Or possibly I'm doing something wrong ?

Best regards
Bartlomiej

0 Kudos

Accepted Solutions
Highlighted
Valued Contributor I
6 Views
Quoting - bartlomiej
Also, I hope, using the new() operator that way does not require any synchronization with other threads?


Yes, it's no more that a call of a class constructor. If constructor is empty and class does not have virtual functions, then this call will be completely optimized away in release build.

View solution in original post

0 Kudos
3 Replies
Highlighted
Valued Contributor I
6 Views
Besides allocation of a memory for the object, you have to construct the object itself:
void* mem = alloc.allocate(1);
sth* ex = new (mem) sth (3.14, 13);
Otherwise you just consider memory block filled with trash as an C++ object which is dead wrong.
See the ISO C++ Standard section 3.8. Object Lifetime and 20.8.2 (may differ in your revision) Allocators.

0 Kudos
Highlighted
New Contributor I
6 Views
Quoting - Dmitriy Vyukov

Oops, yes. I didn't know this. Sorry.
Also, I hope, using the new() operator that way does not require any synchronization with other threads?

0 Kudos
Highlighted
Valued Contributor I
7 Views
Quoting - bartlomiej
Also, I hope, using the new() operator that way does not require any synchronization with other threads?


Yes, it's no more that a call of a class constructor. If constructor is empty and class does not have virtual functions, then this call will be completely optimized away in release build.

View solution in original post

0 Kudos