Solved

Creating Efficient Constant String class literals in C++

Posted on 2004-10-19
7
472 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
Comment Utility
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
Comment Utility
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
Comment Utility

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
Comment Utility
PAQed with points refunded (400)

modulo
Community Support Moderator
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Suggested Solutions

Unlike C#, C++ doesn't have native support for sealing classes (so they cannot be sub-classed). At the cost of a virtual base class pointer it is possible to implement a pseudo sealing mechanism The trick is to virtually inherit from a base class…
Article by: SunnyDark
This article's goal is to present you with an easy to use XML wrapper for C++ and also present some interesting techniques that you might use with MS C++. The reason I built this class is to ease the pain of using XML files with C++, since there is…
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 learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

744 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

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now