Re: C++ dynamic structures
- From: Martin Eisenberg <martin.eisenberg@xxxxxxx>
- Date: Tue, 29 Aug 2006 20:13:16 +0000 (UTC)
googlinggoogler@xxxxxxxxxxx wrote:
Anyway I'm trying to dynamically assign a structure whilst I
read from a file, however my program crashes, and im not sure
why other than that its to do with my memory operations using
new and delete.
You can get pretty far in C++ without ever explicitly managing
memory. I recommend the book Accelerated C++ by Koenig and Moo. In
this case you should be using a container instead of newing arrays,
for instance a vector:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
struct TOKEN
{
TOKEN(string line) : linetoken(line) {}
string linetoken;
};
int main()
{
vector<TOKEN> Tokens;
ifstream ifs("data.txt");
string line;
while(getline(ifs,line))
{
Tokens.push_back(line);
cout << Tokens.back().linetoken << endl;
}
cout << "AAAAAAAA";
return 0;
}
I've given TOKEN a conversion constructor to be able to push strings
onto the vector without an intermediate TOKEN object. Note that the
standard mandates that repeated appending to a vector have linear
amortized complexity, but the example still works if you replace both
occurrences of "vector" with "list".
Doug wrote:
IIRC, I don't think that 'new' calls the ctors of structs when it
allocates them, whereas it does call the ctor for classes.
The only difference between struct and class is the default access
level of unqualified members. The distinction you have in mind is
between POD and non-POD (Googler, that's "Plain Old Data", a
technical term from the C++ standard. You can look it up.) As
std::string is non-POD so is TOKEN, which means that new default-
initializes each array element. The implicitly-defined default
constructor of TOKEN in turn default-constructs its members. It's
true that a POD array would stay uninitialized unless the newing line
ended in (), forcing zero-initialization.
Martin
--
Quidquid latine scriptum sit, altum viditur.
.
- Follow-Ups:
- Re: C++ dynamic structures
- From: Doug
- Re: C++ dynamic structures
- References:
- C++ dynamic structures
- From: googlinggoogler
- Re: C++ dynamic structures
- From: Doug
- C++ dynamic structures
- Prev by Date: Re: Java or C++ College Path
- Next by Date: Re: C++ dynamic structures
- Previous by thread: Re: C++ dynamic structures
- Next by thread: Re: C++ dynamic structures
- Index(es):
Relevant Pages
|