Member Avatar for Member #251199

EDIT: I mucked up the thread title. It should be "Convert Custom type 'String' to std::string"

Hi,

How would I be able to convert a custom type 'String' to a std::string? Just that the function I'm using requires a std::string.

troublesome code:

SetVar::operator char* ()
{
	if (szName == "Passwd")//only create a md5 hash for the password, not anything else
	{
		std::string pwd;
		//here i need to convert 'sVal' from a String to a std::string called 'pwd'
		return md5.getHashFromString(pwd);
	}
	return sVal;
}

types.cpp

// types.cpp
//

#include "types.h"

//
// String
//

String::String()
{
	szStr = NULL;
}

String::String(char *str)
{
	*this = str;
}

String::~String()
{
	if (szStr) {
		free(szStr);
		szStr = NULL;
	}
}

String& String::operator= (char *str)
{
	if (szStr) {
		free(szStr);
		szStr = NULL;
	}

	if (str)
		szStr = strdup(str);
	
	return *this;
}

String::operator char* ()
{
	return szStr;
}

bool String::operator== (char *str)
{
	if (!strcmp(szStr, str))
		return true;
	else
		return false;
}

types.h

// types.h
//

#ifndef TTYPES_H
#define TTYPES_H

#include <windows.h>

typedef unsigned char uchar;
typedef unsigned short ushort;
typedef unsigned int uint;
typedef unsigned long ulong;

#define WSTD_DEL(x) { if ((x)) { delete (x); (x)=NULL; } }
#define WSTD_DELM(x) { if ((x)) { delete[] (x); (x)=NULL; } }

//
// String
//

class String
{
	public:
		String();
		String(char *str);
		~String();

		String& operator= (char *str);
		operator char* ();

		bool operator== (char *str);

	private:
		char *szStr;
};

#endif

Thanks in advance.
vs49688

Dani AI

Generated

Quick summary: the immediate reason the code failed was the lack of a safe way to get a C string out of the custom String so a std::string could be constructed. 's suggestion to add a c_str() accessor is the minimal, practical fix and is what resolved the original poster's problem; and pointed out using c_str() or constructing via a stream as alternatives, and correctly warned about copy/ownership issues.

A more robust approach is to stop managing raw char* buffers in user code and let std::string do it. The following is an example of a safe modern replacement for String that avoids manual allocation and the rule-of-three pitfalls:

class String {
    std::string data_;
public:
    String() = default;
    String(const char* s) : data_(s ? s : "") {}
    String(const std::string& s) : data_(s) {}
    String& operator=(const char* s) { data_ = s ? s : ""; return *this; }
    const char* c_str() const noexcept { return data_.c_str(); }
    explicit operator std::string() const { return data_; }
};

Notes and cautions:

  • Prefer the “rule of zero” (store std::string) so copies and moves are correct without custom copy/assign/dtor. This avoids the crashes ArkM warned about if the raw pointer is shallow-copied.
  • Make c_str() const and return an empty string when the internal pointer would otherwise be null.
  • Avoid implicit conversions that return raw char* (non-const) — they invite lifetime and aliasing bugs. Mark conversions explicit or provide a toStdString()/c_str() accessor.
  • If a hashing helper returns char*, be conscious of ownership and lifetime; prefer APIs that accept or return std::string to eliminate dangling-pointer risks.

These changes keep the original quick fix but make the type safe and maintainable going forward.

Recommended Answers

All 5 Replies

Let start with..

//...
md5.getHashFromString(pwd.c_str());
//...

Try using this routine to convert from cstring to std::string using stringstream
Here is the routine

#include <sstream>
#include <string>

using namespace std;

string convert(char *customString)
{
       stringstream s;
       s << customString;
       string d = s.str();
       return d;

}

Hope that i understood your Question.

The same way std::string does it

class String
{
	public:
		String();
		String(char *str);
		~String();

		String& operator= (char *str);
		operator char* ();
        const char* c_str() {return szStr;} 
		bool operator== (char *str);

	private:
		char *szStr;
};
Member Avatar for Member #251199

thanks guys. Ancient Dragon's solution solved it.

1. By the way, you must define non-trivial copy constructor and assignment operator for this class String (or declare them as private to prevent inevitable program crash if default copy constructor and/or assignment will be called).
2. If you want String to std::string conversion, define it, what's a problem?

String::operator std::string() const
{
    return szStr;
}

3. Avoid using of malloc/strdup/free stuff in C++ programs. Use new/delete operators only.

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.