This is a frustating problem likely experienced by everyone and therefore there (might) be now a "perfect" solution, but my limited skills have impeded me from finding it.

1) I created a plain vanilla text_class that automatically relocates itself when needed.
2) I want to use my text_class with Win32 functions which requires a char *
3) No problem, I can supply an automatic conversion to char * or better a conversion to a
"proxy char * class" that itself has an automatic converstion to char *. (The idea is that the proxy can "prepare" my text_class (like appending a \0 or locking or whatever you want before passing the char *)
4) When the text_class is passed directly as an argument, all is well as the char * never gets exposed elsewhere.
5) But the problem I want to solve is this:
Sooner or later someone will write: const char * pchar=text, where text is an instance of my text_class. Then later, text could independantly be relocated during an insertion of characters, and pchar will points to nowhere and disaster sooner or later.
6) Hence the obvious question: is there a way to permit only a conversion to a temporary variable (such as when passed as an argument as char * or proxy) and never permit to pass it to a normal variable. (Perhpas C++11 "rvalue" is related to this (??), but I don't have C++11, so we need something more traditional)

Well you can do like the standard library does and say that a iterator a pointer to the data of a class is only good until the next time you use the object.

>>Sooner or later someone will write: const char * pchar=text, where text is an instance of my text_class. Then later, text could independantly be relocated during an insertion of characters, and pchar will points to nowhere and disaster sooner or later.

Well sooner or later that "someone" will have to learn to program correctly and not do such a dumb thing. Do like the standard library does, specify that the char pointer provided by your text_class will not be valid after any subsequent use of the text_class object. Better yet, use the std::string class instead of your own version of it.

>>is there a way to permit only a conversion to a temporary variable

No, not that I know of. If you cannot control the destination type (e.g. it has to be "const char*" and not some proxy class), then you cannot detect whether it is going to be temporary or not, or enforce any requirement for it to be temporary.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.