473,322 Members | 1,504 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.

Help with std::string

Hi all,
I want to use std::string instead of char * 's as suggested
at many places in this newsgroup as well as else where, but I am
confused with the way to use it.

For example I have a library built over top of another library which is
C API and my api is in C++. Thus any time I need to call any function
of this C-API, I need to pass the char * while I store them as string
as data member of my classes (see code below). To do so, I have to call
string.c_str() function, but

Q. Is it safe to do so, because I might delete the data in my class
while the C-API might be storing the pointer to that or the c-api might
delete the pointer while I still have reference to the string?

Q. Shall I pass the string into the constructor as reference or shall
I pass as value?
MYCPPAPI(const string & data) or MYCPPAPI(const string data)
I just need to store the passed value in my class MyCPPAPI
If I pass by reference then what are the precautions that need to be
taken?

Q. What precautions should be taken to return the string as reference?

Q. Shall I store the string data member as pointer or just as an
object?
i.e
private:
string data; //or string * data //or const string
data

constructor as
MYCPPAPI(const string & data):_data(data) or
MYCPPAPI(const string & data){
_data = data;
}
or
MYCPPAPI(const string & data){
_data = new string(data); //If _data is string *
} or

///////////////////////////////////// CODE
//////////////////////////////////////////////////////
extern void c_function_call(char * data);
class MyCPPAPI
{
public:
MYCPPAPI(const string & data)
{
this->_data = data;
}
void callCAPIFunction()
{
c_function_call(_data.c_str());
}
private:
string _data;
};
//////////////////////////////////////////////////////////////////////////////////////////////////////

Thanks,
Divick

Jan 11 '06 #1
5 3809
Divick wrote:
Q. Is it safe to do so, because I might delete the data in my class
while the C-API might be storing the pointer to that or the c-api might
delete the pointer while I still have reference to the string?
No. The pointer may be invaildated as soon as you modify or destroy the
string. And you must never call delete or free on that pointer.
Q. Shall I pass the string into the constructor as reference or shall
I pass as value?
MYCPPAPI(const string & data) or MYCPPAPI(const string data)
I just need to store the passed value in my class MyCPPAPI
Pass it as reference.
If I pass by reference then what are the precautions that need to be
taken?
None.
Q. What precautions should be taken to return the string as reference?
None.
Q. Shall I store the string data member as pointer or just as an
object?
As an object. Don't use a pointer unless you need to.
i.e
private:
string data; //or string * data //or const string
data
What would be the advantage of using a pointer?
constructor as
MYCPPAPI(const string & data):_data(data)
This one. But you need to add a constructor body.

or
MYCPPAPI(const string & data){
_data = data;
}
or
MYCPPAPI(const string & data){
_data = new string(data); //If _data is string *
} or

///////////////////////////////////// CODE
//////////////////////////////////////////////////////
extern void c_function_call(char * data);
class MyCPPAPI
{
public:
MYCPPAPI(const string & data)
{
this->_data = data;
}
void callCAPIFunction()
{
c_function_call(_data.c_str());
}
private:
string _data;
};

Jan 11 '06 #2
On 11 Jan 2006 02:01:06 -0800 in comp.lang.c++, "Divick"
<di************@gmail.com> wrote,
Q. Is it safe to do so, because I might delete the data in my class
while the C-API might be storing the pointer to that or the c-api might
delete the pointer while I still have reference to the string?
If the C API stores a pointer to any of your data, that is a
peculiar requirement of that API; it is likely to be awkward for any
number of reasons, and it should be carefully documented how long
the API needs the data to persist, etc..

If it is going to delete a pointer you pass to it, that was not
'new'ed by the API in the first place, then that is a peculiar
requirement of that API and will cause awkwardness, will require
careful documentation etc..

None of that is any different with regard to strings than anything
else.
Q. Shall I pass the string into the constructor as reference or shall
I pass as value?
Pass by value if you need the parameter to be a COPY of the
argument. Pass by reference if you do not want that copying.
Since you will rarely want a string argument to be copied,
most often the parameter should be a const reference.
Q. What precautions should be taken to return the string as reference?
Never return a reference to a local auto string that disappears
before the (now invalid) return value can be used. Never return a
reference to a dynamically allocated string that the caller will
subsequently have to convert to a pointer in order to delete it.
Never return a reference to a static string that will prevent your
function from being used by multiple threads or for multiple
purposes concurrently without them interfering with each other.

So it comes down to, return strings by value. There are probably
exceptions to this rule.
Q. Shall I store the string data member as pointer or just as an
object?


Ordinary member. Do not introduce an extra pointer unless you have
a very specific reason to do so.

Jan 11 '06 #3
>Pass by value if you need the parameter to be a COPY of the
argument. Pass by reference if you do not want that copying.
Since you will rarely want a string argument to be copied,
most often the parameter should be a const reference.


Anyway, why would someone prefer to pass a string by value rather than
by const reference? Never!

Jan 11 '06 #4
On 11 Jan 2006 13:01:16 -0800 in comp.lang.c++, "Jeff Lefebvre"
<je***********@gmail.com> wrote,
Pass by value if you need the parameter to be a COPY of the
argument. Pass by reference if you do not want that copying.
Since you will rarely want a string argument to be copied,
most often the parameter should be a const reference.


Anyway, why would someone prefer to pass a string by value rather than
by const reference? Never!


Example:

string operator+(string left, const string& right)
{
return left += right;
}

Jan 11 '06 #5
Jeff Lefebvre wrote:
Anyway, why would someone prefer to pass a string by value rather than
by const reference? Never!


To avoid explicit copy and have another variable name in scope.

--
Salu2
Jan 11 '06 #6

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

Similar topics

10
by: Angus Leeming | last post by:
Hello, Could someone explain to me why the Standard conveners chose to typedef std::string rather than derive it from std::basic_string<char, ...>? The result of course is that it is...
11
by: Christopher Benson-Manica | last post by:
Let's say I have a std::string, and I want to replace all the ',' characters with " or ", i.e. "A,B,C" -> "A or B or C". Is the following the best way to do it? int idx; while(...
22
by: Jason Heyes | last post by:
Does this function need to call eof after the while-loop to be correct? bool read_file(std::string name, std::string &s) { std::ifstream in(name.c_str()); if (!in.is_open()) return false; ...
19
by: Erik Wikström | last post by:
First of all, forgive me if this is the wrong place to ask this question, if it's a stupid question (it's my second week with C++), or if this is answered some place else (I've searched but not...
8
by: Patrick Kowalzick | last post by:
Dear NG, I would like to change the allocator of e.g. all std::strings, without changing my code. Is there a portable solution to achieve this? The only nice solution I can think of, would be...
6
by: Nemok | last post by:
Hi, I am new to STD so I have some questions about std::string because I want use it in one of my projects instead of CString. 1. Is memory set dinamicaly (like CString), can I define for...
9
by: Divick | last post by:
Hi all, I have a problem related to std::string class. Is it ok to assign a global string variable to a local string object as shown below? I am trying to print the address of local string...
2
by: FBergemann | last post by:
if i compile following sample: #include <iostream> #include <string> int main(int argc, char **argv) { std::string test = "hallo9811111z"; std::string::size_type ret;
6
by: SteelSide | last post by:
Ive searched and searched,but havent been able to get it to work. ----------------- #include <iostream> using namespace std; std::string tempHostNameStr = "s1e2.hidden.thingy.org"; char...
11
by: Jacek Dziedzic | last post by:
Hi! I need a routine like: std::string nth_word(const std::string &s, unsigned int n) { // return n-th word from the string, n is 0-based // if 's' contains too few words, return "" //...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
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
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
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

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.