473,546 Members | 2,243 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

On std::string::c_ str() and const_cast<char *>

I hardly dare ask this given the furore in another thread over strings and
const... My problem is this. I am assured that casting away the constness of
the return value of std::string::c_ str() is an Error according to the Standard.
But I need to pass it to a function (in an old and unpleasant C library, ugh)
which takes an ordinary char*. What should I do? Is it really necessary to make
a fresh copy of the string?

(I'm not asking this from a performance point of view - the string is rarely
likely to be over 20 characters, and in any case it's certainly not a bottleneck
- but just from an aesthetics one: it's already annoying enough that std::string
doesn't gracefully give me a way of getting a plain char* to its data. (Or am I
wrong?))

Thanks in advance,
Tom
Oct 3 '06 #1
5 9180
Tom Smith posted:
I hardly dare ask this given the furore in another thread over strings
and const... My problem is this. I am assured that casting away the
constness of the return value of std::string::c_ str() is an Error
according to the Standard. But I need to pass it to a function (in an
old and unpleasant C library, ugh) which takes an ordinary char*. What
should I do? Is it really necessary to make a fresh copy of the string?

Does the unpleasant C library function alter the data? If not, then simply
cast away the constness.

If it does, then you have to consider:

(1) Is it okay to alter the data at the address specified by c_str?

If so,

(1.a) Just cast away the constness and let it be altered.

If not,

(1.b) You'll have to make a copy.

--

Frederick Gotham
Oct 3 '06 #2
Tom Smith <no************ ***@use.netwrot e:
I hardly dare ask this given the furore in another thread over strings and
const... My problem is this. I am assured that casting away the constness of
the return value of std::string::c_ str() is an Error according to the Standard.
As far as I know, as long as you don't ever try to modify the contents
of the string pointed to by c_str(), you should be fine casting away its
constness.
But I need to pass it to a function (in an old and unpleasant C library, ugh)
which takes an ordinary char*. What should I do? Is it really necessary to make
a fresh copy of the string?
As long as you are 100% totally sure that the function won't try to
modify the char* string, then you should be OK.

--
Marcus Kwok
Replace 'invalid' with 'net' to reply
Oct 3 '06 #3
Tom Smith wrote:
it's already
annoying enough that std::string doesn't gracefully give me a way of
getting a plain char* to its data. (Or am I wrong?))
All existing implementations use contiguous memory.
It may be a requirement in the next standard also.

So if you really need to you could just code using the assumption that
std::string is contiguous.

Oct 3 '06 #4

Tom Smith wrote:
I hardly dare ask this given the furore in another thread over strings and
const... My problem is this. I am assured that casting away the constness of
the return value of std::string::c_ str() is an Error according to the Standard.
No. It is perfectly legitimate to cast away the const using const_cast.
What is not legitimate (read: undefined behaviour) is to then try and
modify the now apparently non-const data.
But I need to pass it to a function (in an old and unpleasant C library, ugh)
which takes an ordinary char*. What should I do? Is it really necessary to make
a fresh copy of the string?
Depends on what the library function does. If it modifies the data then
you do need to make a copy. The std::string class encapsulates its data
and makes available facilities to modify its data through its public
interface. std::string is not designed to be able to handle anything
outside directly modifying the data outside the scope of its public
interface.

However, many functions that take a C-style string passed as a char* do
not and are never intended to modify the data. Such functions (which
may be C or C++) are written with char* rather than const char* in the
signature for a number of reasons, e.g.

1 The function is a legacy function, written before const existed or
was widely supported
2 The programmer was careless in making the code const-correct
3 The programmer did not know of the existence of const

In a case where the parameter should logically be const, but happens
(e.g. for one of the reason above) not to be declared const, that is
exactly the situation const_cast is designed for. It allows you to keep
your code const-correct, by using const declarations and classes that
manage their own data, while still being able to interface with
const-incorrect legacy APIs.

Remember that a cast does not mean "I can't think of another way to
make this work. I hope it doesn't go wrong". A cast means "Dear
compiler, you won't like this code without a cast, but I know exactly
what I'm doing and why. I am casting off all the safety precautions you
usually give me and assuming full responsibility for the correct
behaviour of this code because in this case I know best".

There is no other way to tell the compiler that the API is incorrect
and should have been written to take a const char*, so if you really do
know best then tell the compiler that with a const_cast.

Gavin Deane

Oct 4 '06 #5
Gavin Deane wrote:
Tom Smith wrote:
<snip>

I am assured that casting away the constness of
>the return value of std::string::c_ str() is an Error according to the Standard.
<snip snippety snip>
>But I need to pass it to a function (in an old and unpleasant C library, ugh)
which takes an ordinary char*. What should I do?

Depends on what the library function does. If it modifies the data then
you do need to make a copy. The std::string class encapsulates its data
and makes available facilities to modify its data through its public
interface. std::string is not designed to be able to handle anything
outside directly modifying the data outside the scope of its public
interface.
<more snippage>

Thanks very much Gavin & all other repliers for your advice: very helpful indeed.

- Tom
Oct 4 '06 #6

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

Similar topics

1
17915
by: Matt Garman | last post by:
What is the "best" way to copy a vector of strings to an array of character strings? By "best", I mean most elegantly/tersely written, but without any sacrifice in performance. I'm writing an application using C++ and the STL for handling my data. Unfortunately, I must interact with a (vanilla) C API. I use vectors of strings (for...
17
3799
by: Karl Ebener | last post by:
Hi! I asked a similar question before but then changed everything to using char-Arrays instead of the string class, but I would rather not do this again. So, does anyone know of a string-Class similar to the STL-<string> that supports null-bytes? I tried with standard <string> but this definitely does not support
8
3720
by: Earl Purple | last post by:
On VC++.NET it is implemented like this static int __cdecl compare ( const _Elem *_First1, const _Elem *_First2, size_t _Count ) { // compare [_First1, _First1 + _Count) with [_First2, ...) return (::memcmp(_First1, _First2, _Count));
13
4627
by: Richard | last post by:
vector<char*> m_Text; m_Text.resize(1); char* foo = "FOO"; char* bar = "BAR"; char* foobar = (char*)malloc(strlen(foo) + strlen(bar) + 1); if (foobar) { strcpy(foobar, foo); strcat(foobar, bar); }
4
11698
by: lada77 | last post by:
All, Just wondering if one of you very helpful guru's out there could comment on some odd behaviour I am seeing. I'm betting it is something obvious but I am not experienced enough to tell right away. Here is my code snippet and the results that I am seeing: #include <map> #include <iostream> int
24
17439
by: Marcus Kwok | last post by:
Hello, I am working on cleaning up some code that I inherited and was wondering if there is anything wrong with my function. I am fairly proficient in standard C++ but I am pretty new to the .NET managed C++. It seems to work fine, but everyone knows that programs with errors can still appear to "work fine" :) I am working with VS .NET...
4
2376
by: Jim Langston | last post by:
I'm using a function like this: char TextBuffer; jGet_DropDown_Selected_Text( cc.ddSex, TextBuffer); Where the function is filling in the text buffer. I don't have access to the actual function to change it to a std::string (it's a library function) so I was thinking, well, I could use a std::vector<charinstead of a char array, but...
1
3647
by: Dancefire | last post by:
Hi, everyone, I'm trying to use std::codecvt<to do the encoding conversion. I am using following code for encoding conversion between wchar_t string and char string(MBCS). I am not sure am I right. The code works, but I'm not familiar with the codecvt, and I don't know my way is the right way to do the job. Could you help me to review the...
7
2703
by: puzzlecracker | last post by:
I need to be able to use map<char, T*>, I can make it std::map<std::string, T*>, however, Key is passed by char, hence I would need to call c_str() all the time. What do you suggest?
0
7507
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7435
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7698
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7461
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7794
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6030
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
3492
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
1922
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
747
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.