c++ - One class with a vector data member -
i define class vector data member. class looks follows
class a{ ... private: std::vector<int> v1; ... }; if use operator new allocate memory class a, program ok. however, if memory pre-allocated memory , cast pointer type a*, program crash.
a* = new a; a* b = (a*)pre_allocated_memory_pointer. i need 1 vector variable size , hope memory 1 pre-allocated memory. have idea problem?
an std::vector object requires initialization, cannot allocate memory , pretend you've got vector.
if need control memory solution defining operator::new class.
struct myclass { std::vector<int> x; ... other stuff ... void *operator new(size_t sz) { ... somewhere sz bytes , return pointer them ... } void operator delete(void *p) { ... memory free ... } }; another option instead specify allocate object using placement new:
struct myclass { std::vector<int> x; ... other stuff ... }; void foo() { void * p = ... enough memory sizeof(myclass) ... myclass *mcp = new (p) myclass(); ... later ... mcp->~myclass(); // call destructor ... memory can reused ... } note std::vector manages memory contained elements , therefore you'll need use stl "allocators" if want control memory needs coming from.
Comments
Post a Comment