473,322 Members | 1,480 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,322 software developers and data experts.

How can I better manage strings and memory

Hi,

I am trying to improve some code that I currently have.

I have a simple class called RequestMessage e.g.

class RequestMessage
{
public:
RequestMessage();
~RequestMessage();

string& getMessage()

private:
string origin
string type;
string body;
....
....
string rqstMessage;
};

getMessage formats the private members and stores them in rqstMessage
before returning a reference to it.

string&
RequestMessage::getMessage()
{
ostringstream* message = new ostringstream("Orgin: ");
message << origin << endl;
message << "Type:" << type << endl;
message << "Body: << body << endl;

rqstMessage = message->str();

return rqstMessage;
}

The problem I have, is that I don't like the fact I already have
stored my data in strings, and then use another string to store it all
again in a formatted way.
Is there a better way to do this, without using the additional memory?

Cheers

Oct 19 '08 #1
10 1442
DeveloperDave wrote:
Hi,

I am trying to improve some code that I currently have.

I have a simple class called RequestMessage e.g.

class RequestMessage
{
public:
RequestMessage();
~RequestMessage();

string& getMessage()

private:
string origin
string type;
string body;
....
....
string rqstMessage;
};

getMessage formats the private members and stores them in rqstMessage
before returning a reference to it.

string&
RequestMessage::getMessage()
{
ostringstream* message = new ostringstream("Orgin: ");
message << origin << endl;
message << "Type:" << type << endl;
message << "Body: << body << endl;

rqstMessage = message->str();

return rqstMessage;
}

The problem I have, is that I don't like the fact I already have
stored my data in strings, and then use another string to store it all
again in a formatted way.
Is there a better way to do this, without using the additional memory?
It would be important to know the context. Anyhow, first be sure
you don't leak the "additional memory" for the ostringstream
(this is not Java). Then, what's the role of rqstMessage? Is it
a cache? Did you make measurements that show you *need* it? If
so make it a mutable member and make getMessage() const.
Otherwise just forget about it, and return a string instead of a
reference.

--
Gennaro Prota | name.surname yahoo.com
Breeze C++ (preview): <https://sourceforge.net/projects/breeze/>
Do you need expertise in C++? I'm available.
Oct 19 '08 #2
DeveloperDave wrote:
Hi,

I am trying to improve some code that I currently have.

I have a simple class called RequestMessage e.g.

class RequestMessage
{
public:
RequestMessage();
~RequestMessage();

string& getMessage()

private:
string origin
string type;
string body;
....
....
string rqstMessage;
};

getMessage formats the private members and stores them in rqstMessage
before returning a reference to it.

string&
RequestMessage::getMessage()
{
ostringstream* message = new ostringstream("Orgin: ");
message << origin << endl;
message << "Type:" << type << endl;
message << "Body: << body << endl;

rqstMessage = message->str();

return rqstMessage;
}
This is a memory leak. Why are you newing message? And why are you not
deleteing it? It should simply be declared as a local variable:

ostringstream message;

Let me guess, you're coming from Java?
Oct 19 '08 #3
On Oct 19, 7:34*pm, red floyd <no.spam.h...@example.comwrote:
DeveloperDave wrote:
Hi,
I am trying to improve some code that I currently have.
I have a simple class called RequestMessage e.g.
class RequestMessage
{
public:
* * RequestMessage();
* * ~RequestMessage();
* *string& getMessage()
private:
* *string origin
* *string type;
* *string body;
* *....
* *....
* string rqstMessage;
};
getMessage formats the private members and stores them in rqstMessage
before returning a reference to it.
string&
RequestMessage::getMessage()
{
* *ostringstream* message = new ostringstream("Orgin: ");
* *message << origin << endl;
* *message << "Type:" << type << endl;
* *message << "Body: *<< body << endl;
* *rqstMessage = *message->str();
* *return rqstMessage;
}

This is a memory leak. *Why are you newing message? *And why are you not
deleteing it? *It should simply be declared as a local variable:

* *ostringstream message;

Let me guess, you're coming from Java?
Guys, I'm not coming from java, and I don't want to know that I should
always call delete with new (I know this already). This also isn't
the final code, it is an example to illustrate my problem. Why not
comment that the "..." will cause the code not to compile as well?

The question is:

is it possible to use the member variables to construct a formatted
string, i.e.
Something like

"Orgin:%s\nType:%s\nBody:%s\n"

Replacing the %s with my member variables, "orgin", "type", and
"body", but without storing these in a new string i.e. not storing the
same information twice.
Oct 19 '08 #4
On Oct 19, 12:29*pm, DeveloperDave <davej2...@gmail.comwrote:
Hi,

I am trying to improve some code that I currently have.

I have a simple class called RequestMessage e.g.

class RequestMessage
{
public:
* * RequestMessage();
* * ~RequestMessage();

* *string& getMessage()

private:
* *string origin
* *string type;
* *string body;
* *....
* *....
* string rqstMessage;

};

getMessage formats the private members and stores them in rqstMessage
before returning a reference to it.

string&
RequestMessage::getMessage()
{
* *ostringstream* message = new ostringstream("Orgin: ");
* *message << origin << endl;
* *message << "Type:" << type << endl;
* *message << "Body: *<< body << endl;

* *rqstMessage = *message->str();

* *return rqstMessage;

}

The problem I have, is that I don't like the fact I already have
stored my data in strings, and then use another string to store it all
again in a formatted way.
Is there a better way to do this, without using the additional memory?

Cheers
Without context, it's hard to say. But why not build the message
in a constructor so that the arguments to the contructor are the
components and only one copy of the built message is kept within
the class.

HTH
Oct 19 '08 #5
DeveloperDave wrote:
On Oct 19, 7:34 pm, red floyd <no.spam.h...@example.comwrote:
>This is a memory leak. Why are you newing message? And why are you not
deleteing it? It should simply be declared as a local variable:

ostringstream message;

Let me guess, you're coming from Java?

Guys, I'm not coming from java, and I don't want to know that I should
always call delete with new (I know this already). This also isn't
the final code, it is an example to illustrate my problem. Why not
comment that the "..." will cause the code not to compile as well?
The point wasn't to use delete, but not using 'new' at all for a
variable that is only locally used. If you 'new' the ostringstream,
there's no point in avoiding the string copy.
The question is:

is it possible to use the member variables to construct a formatted
string, i.e.
Something like

"Orgin:%s\nType:%s\nBody:%s\n"
Yes,
Replacing the %s with my member variables, "orgin", "type", and
"body", but without storing these in a new string i.e. not storing the
same information twice.
Without storing the complete string? That depends on what you want to do
with the string.

For only outputting it to console (or file), you could implement a print
function that outputs to ostream&:

RequestMessage::print(std::ostream& message) const
{
message << origin << '\n'
<< "Type:" << type << '\n'
<< "Body:" << body << endl;
}

That way, a client could pretty print the object to cout, to a file
stream, a memory stream or any other custom stream.

--
Thomas
Oct 19 '08 #6
DeveloperDave wrote:
>
The question is:

is it possible to use the member variables to construct a formatted
string, i.e.
Something like

"Orgin:%s\nType:%s\nBody:%s\n"

Replacing the %s with my member variables, "orgin", "type", and
"body", but without storing these in a new string i.e. not storing the
same information twice.
That all depends on what you want to do with the result. If you just
want to output it, then follow Thomas' advice. But don't forget the
data probably will be stored twice because the output stream is buffered!

--
Ian Collins
Oct 19 '08 #7
DeveloperDave wrote:
On Oct 19, 7:34 pm, red floyd <no.spam.h...@example.comwrote:
>DeveloperDave wrote:
>>Hi,
I am trying to improve some code that I currently have.
I have a simple class called RequestMessage e.g.
class RequestMessage
{
public:
RequestMessage();
~RequestMessage();
string& getMessage()
private:
string origin
string type;
string body;
....
....
string rqstMessage;
};
getMessage formats the private members and stores them in rqstMessage
before returning a reference to it.
string&
RequestMessage::getMessage()
{
ostringstream* message = new ostringstream("Orgin: ");
message << origin << endl;
message << "Type:" << type << endl;
message << "Body: << body << endl;
rqstMessage = message->str();
return rqstMessage;
}
This is a memory leak. Why are you newing message? And why are you not
deleteing it? It should simply be declared as a local variable:

ostringstream message;

Let me guess, you're coming from Java?

Guys, I'm not coming from java, and I don't want to know that I should
always call delete with new (I know this already). This also isn't
the final code, it is an example to illustrate my problem. Why not
comment that the "..." will cause the code not to compile as well?
Frankly, it doesn't matter. Your code flat out will not work.

ostreamstring *ss = new ostreamstring("origin: ");
ss << "Hello";

Will *NOT* work. There is no operator<< defined which takes a
ostreamstring* as a left hand side.
Oct 19 '08 #8
DeveloperDave wrote:
On Oct 19, 7:34 pm, red floyd <no.spam.h...@example.comwrote:
>DeveloperDave wrote:
>>Hi,
I am trying to improve some code that I currently have.
I have a simple class called RequestMessage e.g.
class RequestMessage
{
public:
RequestMessage();
~RequestMessage();
string& getMessage()
private:
string origin
string type;
string body;
....
....
string rqstMessage;
};
getMessage formats the private members and stores them in rqstMessage
before returning a reference to it.
string&
RequestMessage::getMessage()
{
ostringstream* message = new ostringstream("Orgin: ");
message << origin << endl;
message << "Type:" << type << endl;
message << "Body: << body << endl;
rqstMessage = message->str();
return rqstMessage;
}
[...]
The question is:

is it possible to use the member variables to construct a formatted
string, i.e.
Something like

"Orgin:%s\nType:%s\nBody:%s\n"

Replacing the %s with my member variables, "orgin", "type", and
"body", but without storing these in a new string i.e. not storing the
same information twice.
You don't need to store the result into a data member, at all.
For most purposes, outputting to a stream is the best solution,
which you can do as suggested by Thomas or, more idiomatically,
writing your own stream inserter (operator <<). Of course, too,
the inserter may just forward the work to print(std::ostream &).
In short, if you are formatting then use the C++ idioms for
formatting.

Otherwise, for the simple need you ask about, you can just
concatenate:

// note: not compiled
std::string
RequestMessage::getMessage() const
{
return "Orgin:" /*[sic]*/ + m_origin + "\n"
+ "Type:" + m_type + "\n"
+ "Body:" + m_body + "\n"
;
}

It's not an approach which defies the centuries but it's an
approach :-)

If this doesn't answer your question you have to give us more
details.

--
Gennaro Prota | name.surname yahoo.com
Breeze C++ (preview): <https://sourceforge.net/projects/breeze/>
Do you need expertise in C++? I'm available.
Oct 19 '08 #9
On Oct 19, 10:49*pm, Gennaro Prota <gennaro/pr...@yahoo.comwrote:
DeveloperDave wrote:
On Oct 19, 7:34 pm, red floyd <no.spam.h...@example.comwrote:
DeveloperDave wrote:
Hi,
I am trying to improve some code that I currently have.
I have a simple class called RequestMessage e.g.
class RequestMessage
{
public:
* * RequestMessage();
* * ~RequestMessage();
* *string& getMessage()
private:
* *string origin
* *string type;
* *string body;
* *....
* *....
* string rqstMessage;
};
getMessage formats the private members and stores them in rqstMessage
before returning a reference to it.
string&
RequestMessage::getMessage()
{
* *ostringstream* message = new ostringstream("Orgin: ");
* *message << origin << endl;
* *message << "Type:" << type << endl;
* *message << "Body: *<< body << endl;
* *rqstMessage = *message->str();
* *return rqstMessage;
}
* * *[...]
The question is:
is it possible to use the member variables to construct a formatted
string, i.e.
Something like
"Orgin:%s\nType:%s\nBody:%s\n"
Replacing the %s with my member variables, "orgin", "type", and
"body", but without storing these in a new string i.e. not storing the
same information twice.

You don't need to store the result into a data member, at all.
For most purposes, outputting to a stream is the best solution,
which you can do as suggested by Thomas or, more idiomatically,
writing your own stream inserter (operator <<). Of course, too,
the inserter may just forward the work to print(std::ostream &).
In short, if you are formatting then use the C++ idioms for
formatting.

Otherwise, for the simple need you ask about, you can just
concatenate:

* *// note: not compiled
* *std::string
* *RequestMessage::getMessage() const
* *{
* * * *return "Orgin:" /*[sic]*/ + m_origin + "\n"
* * * * * * * + "Type:" * * * * *+ m_type * + "\n"
* * * * * * * + "Body:" * * * * *+ m_body * + "\n"
* * * * * * * ;
* *}

It's not an approach which defies the centuries but it's an
approach :-)

If this doesn't answer your question you have to give us more
details.

--
* *Gennaro Prota * * * * | * * * * * name.surname yahoo.com
* * *Breeze C++ (preview): <https://sourceforge.net/projects/breeze/>
* * *Do you need expertise in C++? * I'm available.
Thanks for the constructive suggestions. I will eventually be writing
the data to a stream, so I guess passing that stream in writing to it,
is the best approach.
Cheers.
Oct 19 '08 #10
DeveloperDave wrote:
Guys, I'm not coming from java, and I don't want to know that I should
always call delete with new (I know this already). This also isn't
the final code, it is an example to illustrate my problem. Why not
comment that the "..." will cause the code not to compile as well?
I don't think you get the point. The fact that you used 'new' in a
place where it's not needed (and in fact wrong) shows that you have a
bad approach at C++ programming. It's imperative to get rid of these bad
habits if you want to become a good C++ programmer.

There are many reasons why you should avoid 'new' in a situation like
you wrote:

- Allocating a local object with 'new' is usually much less efficient
than instantiating it directly. Stack-allocation is usually much faster
and efficient than heap-allocation.

- When you allocate something with 'new' and handle it with a raw
pointer, you always have the risk of a memory leak, even if you
seemingly 'delete' the object afterwards. Functions can have surprising
hidden exit points. C++ does not have garbage collection, so you have to
learn to live with this.

- Your code doesn't even work. You are calling "message << something"
even though 'message' is a *pointer*, not an ostringstream object. You
can't apply the << operator to a pointer.
Oct 20 '08 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

133
by: Gaurav | last post by:
http://www.sys-con.com/story/print.cfm?storyid=45250 Any comments? Thanks Gaurav
39
by: bazad | last post by:
Hi, I am not using C all the time. I have a general understanding of C and nothing else. The recent reply to use strlcpy and strlcat showed me that I am not aware of the best and safe...
5
by: yezi | last post by:
If the file is very huge, but it is needed to be read in the memory, how to manage the memory,? Thanks for any comment.
11
by: seberino | last post by:
Suppose a C extension locally built an array of PyObject* 's as follows... my_array = malloc(n * sizeof(PyObject*)); for (i = 0; i < n; i++) { my_array = PyList_New(0); } Q1: Must I do a...
21
by: c | last post by:
Hi everybody. I'm working on converting a program wriiten on perl to C, and facing a problem with concatenate strings. Now here is a small program that descripe the problem, if you help me to...
4
by: CoreyWhite | last post by:
/* WORKING WITH STRINGS IN C++ IS THE BEST WAY TO LEARN THE LANGUAGE AND TRANSITION FROM C. C++ HAS MANY NEW FEATURES THAT WORK TOGETHER AND WHEN YOU SEE THEM DOING THE IMPOSSIBLE AND MAKING...
28
by: hlubenow | last post by:
Hello, I really like Perl and Python for their flexible lists like @a (Perl) and a (Python), where you can easily store lots of strings or even a whole text-file. Now I'm not a...
12
by: Bill Jackson | last post by:
I have a dictionary of dictionaries where the keys are typically very long tuples and repeated in each inner dictionary. The dictionary representation is nice because it handles sparseness...
34
by: pamela fluente | last post by:
I would like to hear your *opinion and advice* on best programming practice under .NET. Given that several time we cannot change: MyCollection.Clear into the instantiation of a NEW...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.