C++ Struct initialisation problem
This c++ code is working fine , however memory validator says that I am using a deleted pointer in: grf->filePath = fname; Do you have any idea why ? Thank you.
Dirloader.h
// Other code
class CDirLoader
{
public:
struct TKnownGRF
{
std::string开发者_JS百科 filePath;
DWORD encodingType;
DWORD userDataLen;
char *userData;
};
// Other Code
CDirLoader();
virtual ~CDirLoader();
Dirloader.cpp
// Other code
void CDirLoader::AddGroupFile(const std::string& _fname)
{
// Other code including std::string fname = _fname;
TKnownGRF *grf = new TKnownGRF;
grf->filePath = fname;
delete grf; // Just for testing purposes
P.S.: This is only an code extract. Of course if I define a struct TKnownGRF inside .cpp and use it as an actual object, gfr.filepath = something, instead of pointer grf->filepath=something, than it is ok, but I do need to have it inside *.h in CDirLoader class, due to many other vector allocations.
Since the function returns void
void CDirLoader::AddGroupFile(const std::string& _fname)
the question is what are you going to do with grf
?
Are you going to delete
it? If so, then, why do a new
? you can just declare a TKnownGRF
variable on the stack! In that case, _fname
is not contributing to the logic of this method.
I guess that the class CDirLoader
has a member variable of type TKnownGRF
, say grf_
, and that need to be used in the AddsGroupFile()
method, e.g.:
grf_.filepath = _fname;
Does this happen to be using an older version of STL, say, VC6, and running multithreaded? Older versions of STL's string class used a reference counted copy on write implementation, which didn't really work in a multithreaded environment. See this KB article on VC 6.
Or, it's also possible that you are looking at the wrong problem. If you call std::string::c_str()
and cache the result at all, the cached result would probably be invalidated when you modified the original string
. There are a few cases where you can get away with that, but it's very much implementation specific.
精彩评论