STL and pointer/reference question
Hi all,
Im rather new to C++ (I´m changing from Java to C++), so please bear with me.
I have a question about STL and returning a vector array
from a static method.
How do I do it correctly, so that the function contructs
a vector that can be returned to the caller. I know if I
create a local object from a class and return it`s reference, it will point to null (if I´m rigth) after the
function call. So the object should be created with the new
operator. But how do I do it with template call??
I just get errors when I try to compile.
It should go something like this(please, do correct my syntax, pointers and references are used very wrong, I think):
static &vector<MyClass> loadFromFile()
{
vector<MyClass> *data = NULL;
try
{
// load from file and populate the vector
}
catch(...)
{ }
return &data;
}
help apprecitaed!
-mark
ps. could somebody tell me where to fing a decent
standard C++ API (yes, I`m migrating from Java to C++). All I have found are rather hard to use / read or incomplete.
Thank you.
Re: STL and pointer/reference question
Quote:
Originally posted by halmark6Z
How do I do it correctly, so that the function contructs
a vector that can be returned to the caller.
A vector has proper copy semantics, so there is no need to be using references or pointers.
Code:
#include <vector>
class MyClass
{
};
static std::vector<MyClass> loadFromFile(); // if you really need a static function
std::vector<MyClass> loadFromFile()
{
std::vector<MyClass> data;
try
{
// load from file and populate the vector
}
catch(...)
{ }
return data;
}
int main()
{
std::vector<MyClass> M;
M = loadFromFile();
}
The code is much more easier than you thought it would be.
Quote:
I know if I create a local object from a class and return it`s reference,
Return it by value (as my code does above), not by reference.
Quote:
it will point to null (if I´m rigth) after the
function call. So the object should be created with the new
operator.
You're right, you do come a Java background, since you do not need to create an object with "new" in C++. ;)
Quote:
It should go something like this(please, do correct my syntax, pointers and references are used very wrong, I think):
Again, no need to use pointers or references.
Quote:
ps. could somebody tell me where to fing a decent
standard C++ API (yes, I`m migrating from Java to C++). All I have found are rather hard to use / read or incomplete.
Get "Accelerated C++" by Koenig & Moo.
Regards,
Paul McKenzie