?
Solved

Creating Efficient Constant String class literals in C++

Posted on 2004-10-19
7
Medium Priority
?
491 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

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say 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

This article will show you some of the more useful Standard Template Library (STL) algorithms through the use of working examples.  You will learn about how these algorithms fit into the STL architecture, how they work with STL containers, and why t…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
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.

770 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