ptr to dynamic array lifetime and scope

Started by
17 comments, last by Convict@Large 22 years ago
Sorry Oluseyi I do not mean to spurne string/STL or whatnot for the sake of it. I am on a deadline atm to get a demo done for a milestone and I allready have a struct similiar to DArray which is almost working (only needing an assignment operator added by the sounds of it). If I add the assignment operator then I should have it working and then I can get on with trying to meet the deadline.

To recode the engine to use std::string would take too long atm so I will continue to use my bodged struct until after the review. I will look at the situation then and decided what to do (use std::string or not) then.

No offence was ment.

Cheers,

Convict@Large

"I code therefore I am" Anon
DanielB - Slayer of Bugs
Advertisement
quote:Original post by Convict@Large
Ah is that the ''='' operator by any chance? So I overload the = operator so that is copies the data between them?

Yup. Note, though that operator=() can be implemented in terms of the copy ctor and the std::swap() function, if you employ a few nifty tricks.

Here''s a demonstration of those nifty tricks:


  class String{public:	String() : rep_(0) {}	String( const String& other )	{		setString(other.rep_);	}	explicit String( char *string )	{		setString( string );	}	String& operator=( String& other )	{		String temp(other);		Swap(temp);		return *this;	}	~String() 	{ 		delete [] rep_; 	}	const char* c_str() const	{		return rep_;	}private:	void setString( const char *string )	{		rep_ = new char[strlen(string) +1];		strcpy(rep_,string);	}	void Swap( String& other )	{		std::swap(rep_, other.rep_);	}private:	char* rep_;};  


The "nifty" tricks can be seen in the private helper functions. setString() is a helper for both copy and conversion ctors, and Swap is a helper for the assignment operator. You might like to ponder on what the assignment operator is doing and why.

I''m now going to issue the traditional disclaimer that this is not a class I use in my own code, it''s merely presented for exposition purposes.

[C++ FAQ Lite | ACCU | Boost | Stroustrup on Learning C++]
quote:Original post by Oluseyi
How can you learn more about the STL if you ignore what it provides? (Oxymoron, ''innit?)

Well, he *is* learning about the demands that the STL makes on a contained type, which he''ll need to learn at some point in using the STL.

[C++ FAQ Lite | ACCU | Boost | Stroustrup on Learning C++]
quote:Original post by SabreMan
Yes, since the internal storage of string is guaranteed to be contiguous. It should work quite well with winsock. Just be aware that the returned pointer points to data that still belongs to the string, so you must not attempt anything that directly manipulates the data via the pointer.


Correct me if I'm wrong, but I'm pretty sure that std::string's internal storage is NOT required to be contiguous (which is why you'd probably use c_str() instead of data() for retrieving a C-style string).

[edited by - kvh on April 19, 2002 12:04:49 PM]
quote:Original post by SabreMan

      	String& operator=( String& other )	{		String temp(other);		Swap(temp);		return *this;	}    

quote:You might like to ponder on what the assignment operator is doing and why.


I am wondering why you are swapping contents of this._rep with temp._rep why not just copy temp._rep into this._rep? I looked in MSDN and it gave this example for operator=:

    class Point{public:    Point &operator=( Point & );  // Right side is the argument.    ...};// Define assignment operator.Point &Point::operator=( Point &ptRHS ){    _x = ptRHS._x;    _y = ptRHS._y;    return *this;  // Assignment operator returns left side.}      

MSDN does not seem to swap values, I am confused as to why you are doing this...

And yes I like to figure out how code works before I use it :D

Cheers,

Convict@Large

[edited by - convict@large on April 19, 2002 11:58:21 AM]
DanielB - Slayer of Bugs
quote:Original post by kvh
Correct me if I''m wrong, but I''m pretty sure that std::string''s internal storage is NOT required to be contiguous

Yes, I didn''t state that very well. Internally, std::string does not have to store it''s data contiguously. However, the c_str() and data() member functions always return a pointer to a contiguous array.

[C++ FAQ Lite | ACCU | Boost | Stroustrup on Learning C++]
Ah, thanks for pointing that out.

I thought data() was similar to &str[0], since MSDN told me:

quote:
The member function returns a pointer to the first element of the sequence (or, for an empty sequence, a non-null pointer that cannot be dereferenced).


but the SGI docs prove you right:

quote:
Returns a pointer to an array of characters, not necessarily null- terminated, representing the string''s contents. data() is permitted, but not required, to be identical to c_str(). The first size() characters of that array are guaranteed to be identical to the characters in *this. The return value of data() is never a null pointer, even if size() is zero.

I think using std::string as a buffer for the wire is gross misuse.

I assume you''re doing asyncronous IO and/or using threads to send the data (otherwise there''s not much point in building a packet queue)
What you really want is a circular memory pool, and I like adding stream operators. That way the packets are serialized once, and never copied after that. There is scatter/gather IO which you could use to prevent any copies, but it means you have to maintain the lifetime of any object pointed to by the sgio and it makes applying encryption and/or compression difficult as you would need sg versions of those functions and they would trash the original items. So you kinda need one copy anyway.


  		template<typename T>		inline StreamBuffer& operator<<(StreamBuffer& stream, const T& lhs)			{			StreamBuffer::tyBuffer::iterator it = stream.itWrite + sizeof(T);			assert(it <= stream.vBuffer.end());			*(T*)&*stream.itWrite = lhs;			stream.itWrite=it;			return stream;			}		template<typename T>		inline StreamBuffer& operator<<(StreamBuffer& stream, const T* lhs)			{			//Do not serialize raw pointers, use MKH::Memory::SerializingPointer			char CompileTimeAssertion[0];			return stream;			}  


Magmai Kai Holmlor

"Oh, like you''ve never written buggy code" - Lee

[Look for information | GDNet Start Here | GDNet Search Tool | GDNet FAQ | MSDN RTF[L] | SGI STL Docs | STFW | Asking Smart Questions ]

[Free C++ Libraries | Boost | ACE | Loki | MTL | Blitz++ ]

Shamelessly ripped from Oluseyi
- The trade-off between price and quality does not exist in Japan. Rather, the idea that high quality brings on cost reduction is widely accepted.-- Tajima & Matsubara
you know its funny, after reading most of this (especially the first reply by saberman) it makes me wonder about some things. first off, the struct presented does NOT show any form of destructor hence the dynamically created array cant be destroyed automagically by the compiler once the varible goes out of scope. so a default copy should work fine unless STL is borken in some way. not trying to flame or anything, but doesnt the default ctor and dtor suppsed to do nothing (except deal with filling the vtable if needed)? also i never had something that i newed to a local varible (like he is doing) which the pointer was then copied to a global storage area (much like what sdt::list must be doing) have the object i created automagically get deleted when the tmp pointer went out of scope. its just an observation i am making. what is the correct result for a compiler for the following code?


  char *globalPtr=NULL{   char *tmpPtr = new char[10];   globalPtr = tmpPtr;}// is globalPtr valid still?// if is then his original code should work     

This topic is closed to new replies.

Advertisement