Void* pointer problem
Pretty new to c++, i have a rather (i think) stupid question开发者_JAVA百科 about a piece of code :
class DataStream
{
protected:
 DataStream(void) { };
public:
 DataStream(int Length); 
 ~DataStream(void);
...
 void* DataPtr;
 int Length;
};
I do have a class similiar to this and i want to assign to DataPtr a pointer to some data allocated. When i do
DataStream::DataStream(int length)
{
char* arr = new char[length];
this->DataPtr = arr;
this->Length = length;
} 
All i get is corrupting the class (the length variable assume strange values) and the dataptr is not the same as the arr pointer. Why is that? What am i missing?
EDIT for information :
Windows Platform, Visual Studio 2010, The implementation is just that (done in the constructor). The including class is a simple EMPTY class with only a constructor that calls in return the constructor of the DataStream class. The class name is ShaderFormat. In the main app the only lines are
ShaderFormat* sf = new ShaderFormat();
DataStream* ds = sf->Save();
I was not directly referencing DataStream in the main app, only the shaderformat classes. (that was the problem it seems) Why is that?
When managing dynamic resources like that in a class, remember the rule of three. You need:
- copy constructor to make a copy (or increment a reference count) of the resource,
- copy assignment operator - same,
- destructor to release the resource if not referenced anymore.
Number of tools is available to ease this management:
- Plain std::vector<char>as member of your class can probably solve your particular array problem - it manages memory for you and gives you control over length of the buffer, and it is fully copyable.
- Privately inheriting from boost::noncopyabledisables all copy semantics. This might be suitable for non-sharable resources.
- Boost Smart Pointers library provides set of classes with scoped and reference-counted semantics for managing pointers and arrays.
Getting deeper into C++ development you will find that you work less with bold pointers and more with tiny wrapper classes and references.
Could you try to shrink your example to a complete yet small one exhibiting the behavior? I see no reason that assignment would affect other members of the object .
what about casting arr to void* and when you need it casting it to char* ?
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论