STL String madness

Started by
4 comments, last by AndyGeers 17 years, 12 months ago
I am totally at my wits' end here, pulling my hair out and so on, getting some totally bizarre behaviour... I have a class like so:

#include <string>

class CXTemplate
{
private:
std::string m_strName;

public:
CXTemplate(const std::string& strName) : m_strName(strName) { }
const std::string& GetName() const { return m_strName; }
}

But when I try to use it:

CXTemplate* t = new CXTemplate("Frame");
CLog::Get()->Log(t->GetName().c_str());

... it just logs the word "(null)" and I get all sorts of crashes and stuff if I try to use it. I just don't get it!
Advertisement
I would really return that string by value, not reference.
Quote:Original post by RDragon1
I would really return that string by value, not reference.


Any particular reason? It's not returning a stack-local variable or anything...

OP: Nothing visibly wrong with the code posted. Chances are your string is getting clobbered by buffer overflows or the like elsewhere in the program, or your Log function is broken. Suggest stepping through with a debugger?
What does "std::cout << t->GetName()" produce?

Obviously, if it's something valid, the problem is in your logger.
Quote:Original post by leiavoia
What does "std::cout << t->GetName()" produce?

Obviously, if it's something valid, the problem is in your logger.


I tried his code with cout earlier on before the server stopped talking to me { =( } and it worked.

As MaulingMonkey suggested, the problem is probably with your logger.

It could also be that your actual code is more complicated than that and you are doing something else wrong.
Thanks for taking the time to help, people.

As predicted, it was some other problem. The full definition of the CXTemplate class was like this:

class CGraphics;class CXTemplate{public:	typedef bool (CGraphics::*TEMP_HANDLER)(CMesh* pMesh, CXFileObject*);private:	TEMP_HANDLER m_pHandler;								std::string m_strName;...}


... and it seems that once the full definition of CGraphics got pulled in the code that used CXTemplate, it affected the memory layout. It's a minor shame to have to introduce a dependency on Graphics.h into all files that use XTemplate.h, but not the end of the world - at least it works now!

This topic is closed to new replies.

Advertisement