C ++ allocates memory without activating constructors

I am reading the values ​​from a file that I will keep in memory when I read them. I read here that the correct way to handle a memory location in C ++ is to always use new / delete, but if I:

DataType* foo = new DataType[sizeof(DataType) * numDataTypes];

This will then call the default constructor for each instance created, and I don't want this. I was going to do this:

DataType* foo;
char* tempBuffer=new char[sizeof(DataType) * numDataTypes];
foo=(DataType*) tempBuffer;

But I thought that it would be something incomprehensible to some type - unpreparedness. So what should I do?

And now, examining this question, I saw that some people say that arrays are bad and vectors are good. I tried to use arrays more because I thought I was a bad boy, filling my programs (what I thought) with slower vectors. What should i use?

+5
7

!!! , , ( myVector.reserve(numObjects), .).

, .

std::vector<DataType> myVector; // does not reserve anything
...
myVector.reserve(numObjects); // tells vector to reserve memory
+7

::operator new .

DataType* foo = static_cast<DataType*>(::operator new(sizeof(DataType) * numDataTypes));

::operator new over malloc , new_handlers .. ::operator delete

::operator delete(foo);

new Something, , , new .

(, ) , - . , ,

DataType dt;
read(fd, &dt, sizeof(dt));

, .

, ?

+4

new char[], , , . ++ " " ?

, std::vector, , , .

+2

. ( push_back ), , .

+1
vector<DataType> dataTypeVec(numDataTypes);

, ( sizeof).

+1

, , , ( ).

+1

Based on what others said, if you ran this program while connecting in a text file integers that populated the data field below, for example:

./allocate < ints.txt

Then you can do:

#include <vector>
#include <iostream>

using namespace std;

class MyDataType {
public:
  int dataField;
};


int main() {

  const int TO_RESERVE = 10;

  vector<MyDataType> everything;
  everything.reserve( TO_RESERVE );

  MyDataType temp;
  while( cin >> temp.dataField ) {
    everything.push_back( temp );
  }

  for( unsigned i = 0; i < everything.size(); i++ ) {
    cout << everything[i].dataField;
    if( i < everything.size() - 1 ) {
      cout << ", ";
    }
  }
}

Which for me with a list of 4 integers gives:

5, 6, 2, 6
+1
source

All Articles