Solved

Creating Efficient Constant String class literals in C++

Posted on 2004-10-19
7
478 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
  • 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

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.

809 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