Solved

Creating Efficient Constant String class literals in C++

Posted on 2004-10-19
7
485 Views
Last Modified: 2012-06-27
I am trying to figure out a way to create compile-time string literals for my custom string class that could be passed in place of "const String &" parameters, such that this parameter passing (1) would not create temporary string copies and (2) would not require counting string characters at runtime. The goal is to achieve the following:

void fn_taking_string_literal(const GString &str) { ... }

//Called as:
fn_taking_string_literal(GSTR("literal text"));

... where GSTR() is some kind of a macro, which generates a fake GString efficiently, without actually counting or copying characters.


My application was using such a technique with Visual Studio 6, however it stopped working once I ported to 7 (.NET), since studio 7 now puts string literals in CONST segment, crashing if they are ever modified. I am looking for a technique with similar syntax that can be implemented under studio 7. [Note that if anyone knows of a compiler option I can use to avoid strings being read-only, it would also help].


Below are the necessary details of my string class implementation, and my original GSTR macro.

The string class is implemented as simply a pointer to an allocated GStringHeader, which stored a length integer followed by string data:


struct GStringHeader
  {
  UInt      Length;
  char      Data[4]; // Data + trailing zeros
                    // More is allocated as necessary for this array
  };

class GString
  {
  GStringHeader      *pData;      
public:

  GString()      
    { pData = &GStringNullHeader; }

  // Constructor, does string copy
  GString(const GString &str);
  GString(const char *);
  ...
  };


// String dummy object used for literal conversion
class GConstString
  {
public:
  union {
    char      *pData;
    UInt      *pSize;
    };

  GConstString(char *p, UInt size)
    { pData = p; *pSize = size;  }

  operator const GString * ()
    { return ((const GString*) this); }
  };

#define GSTR(str) *GConstString("    " str##"\0\0\0", sizeof(str)-1)


With this implementation, I could indeed write code such as:

fn_taking_string_literal(GSTR("literal text"));

Furthermore, the implementation was efficient – the compiler generated string literal was reinterpreted directly as allocated string class data. The only inefficiency was that the size was always stored in front of string data, but that was still much more efficient then copying all the characters and/or counting the length.

With visual studio 7 this no longer works, since any access such as

  char *ptext = "text";
  ptext[0] = 'c';

causes an access violation.


I tried switching a GConstString constructor to

GConstString(char p[], UInt size)
  { pData = p; *pSize = size;  }

and that, surprizingly, did not solve the problem.


Does anyone have any suggestions?
0
Comment
Question by:mikeant78
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
7 Comments
 
LVL 12

Expert Comment

by:OnegaZhang
ID: 12353246
CString   and std::string are all efficient when you don't need to write to it, for they are COW (copy on write).

if you still doubt of performance of COW, you can pass referrence to string/CString instead of creating another class.

Or use BSTR, but you have to convert constant string to BSTR manually.

welcome to www.fruitfruit.com
0
 

Author Comment

by:mikeant78
ID: 12353528
I understand the implications of COW, and implementation details of various existing string classes. No matter what implementation is, it would at the least need to compute the string length on the initial string construction (that is, if it chooses to store the length in addition to the trailing zero, as it should).

My question instead focuses on how to reinterpret a C++ string literal, i.e. a quoted string, as string class of choice. The goal is to optimize/elimiate the initial construction of a string, not optimize its passing mechanism once it has been constructed.

I would like to have a macro, or some kind of inline mechanism that would allow me to statically initalize {string_length, string_data} tuple that can then be converted/cast into a string class.
0
 

Author Comment

by:mikeant78
ID: 12666857

I have actually figured out the solution which works... If i put in pragmas

#pragma data_seg(".rwdata")
#pragma const_seg(".rwdata")

in my original code (discussed above) it works correctly in the Visual Studio 7, because these pragmas cause strings to go into a writable segment instead of read-only segment.


Since I did not receive any real assistance in this question, I would like my points refunded, if possible.



0
 

Accepted Solution

by:
modulo earned 0 total points
ID: 12723902
PAQed with points refunded (400)

modulo
Community Support Moderator
0

Featured Post

On Demand Webinar: Networking for the Cloud Era

Ready to improve network connectivity? Watch this webinar to learn how SD-WANs and a one-click instant connect tool can boost provisions, deployment, and management of your cloud connection.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Written by John Humphreys C++ Threading and the POSIX Library This article will cover the basic information that you need to know in order to make use of the POSIX threading library available for C and C++ on UNIX and most Linux systems.   [s…
Introduction This article is the first in a series of articles about the C/C++ Visual Studio Express debugger.  It provides a quick start guide in using the debugger. Part 2 focuses on additional topics in breakpoints.  Lastly, Part 3 focuses on th…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

691 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question