473,804 Members | 3,462 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Smart pointer for arrays of structs?

Hi,

I have some data which is stored as plain old C structures. Until now I've
had arrays of these structs on stack but due to stack overrun I need to move
these to heap.
I've been trying out some smart pointers to help but so far the
implementation I've been dealing with has had problems with [] operator
since it could conflict when using the same class with "unsigned char".

Do you have any recommendations for smart pointers able to work with arrays?

I would need something like:

ptr = (new or malloc) MY_STRUCT [16];

ptr[i].member

Thanks.

-- Henrik
Dec 26 '06
12 5224
If mytype is a C struct that needs to be used with C headers too (thus
you can't give it any constructors), then you can still do it using a
0-initialised element to constructor your vector or call resize. You
just have to create one such struct and use it to initialise all the
other members.
Yes in my case it's a C struct.
I don't really like your suggestion about using a preinitialized value
though. It requires even more code then other proposed solutions.
Note that you could use a "static" instance of one.
That is really not a good idea in my case since the code is used among
different projects and modules. It only makes it harder to understand.
Beware, by the way, that &v[0] or &v.front() is undefined behaviour if
v is an empty vector, so you should check for this and probably return
a NULL pointer when that is the case.
This is not the case for me fortunatly. In those places where I need it it
has been resize()'d in the constructor prior to any use.

Thanks.

-- Henrik
Dec 28 '06 #11

Henrik Goldman wrote:
Note that you could use a "static" instance of one.

That is really not a good idea in my case since the code is used among
different projects and modules. It only makes it harder to understand.
It doesn't really need to be static, a const global will do. It should
be initialised in one module though. Although globals are normally
evil, if it's const it is less evil.

const mytype zero_my_type = { 0, 0, 0, 0 }; // etc

then my_type_vec.res ize( 50, zero_my_type );

If you prefer you can scope the instance and expose the function but
you really haven't gained a lot.
Beware, by the way, that &v[0] or &v.front() is undefined behaviour if
v is an empty vector, so you should check for this and probably return
a NULL pointer when that is the case.

This is not the case for me fortunatly. In those places where I need it it
has been resize()'d in the constructor prior to any use.
I have wrapper "buffer" classes that will wrap arrays or vectors and it
also has a begin() and end() which are guaranteed to be pointers. (I
have two such classes, one for const and one for non-const). buffer is
fairly trivial to write and looks something like this:

template < typename T >
class buffer
{
T * itsData;
size_t itsSize;
public:
buffer( T* d, size_t sz ) : itsData( d ), itsSize( sz ) {}

buffer( vector< T & vec )
: itsData( vec.empty() ? 0 : &vec[0] ),
itsSize( vec.size() )
{
}

buffer() : itsData( 0 ), itsSize( 0 )
{
}

buffer( T* first, T* last ) : itsData( first ), itsSize( last -
first )
{
}

T* begin() const { return itsData; }
T* end() const { return itsData + itsSize; }
bool empty() const { return itsSize == 0; }
size_t size() const { return itsSize; }
};

Define const_buffer exactly the same but with const T* pointers and
const std::vector<T& and add this constructor

const_buffer( const buffer<T& nc_buf ) : itsData( nc_buf.begin()
), itsSize( nc_buf.size() )
{
}

Note that these classes do not take ownership of the buffer so there is
no memory handling issue. You might be surprised that begin() and end()
are const methods even in buffer. They are because you cannot modify
the pointers themselves, only what they point to. The class is
non-mutable (cannot be changed) other than assigning it to another
instance. Note that its constructors that take one parameter are
purposely non-explicit.

Now with a vector that might be empty and passing it to a functino that
takes a pointer and size that might be empty you can always pass in

buffer( theVec ).begin() (or const_buffer( theVec ).begin() if
appropriate)

Dec 28 '06 #12
Henrik Goldman wrote:
Thank you Gianni, Jim, Peter, for your answers.

It seems to be a good choice. It certainly saved me from a day of work
trying to get a smart pointer class working to do the same job.

The way I use it is:

vector <mytypev;

v.resize(nEleme nts);
and then
memset(&v[0], 0, sizeof(mytype) * v.size());

It's too bad I cannot do all the initialization at once. However the data
needs to be zero initialized and have a certain size.
static const mytype t;
vector<mytype v;
v.resize(nEleme nts, t);
--
Clark S. Cox III
cl*******@gmail .com
Dec 28 '06 #13

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
2157
by: christopher diggins | last post by:
I would like to survey how widespread the usage of smart pointers in C++ code is today. Any anecdotal experience about the frequency of usage of smart pointer for dynamic allocation in your own code or other people's code you have come across would be appreciated. I am also trying to identify the likelihood nad frequency of scenarios where smart pointer solutions would not be appropriate, i.e. for some reason such as performance or...
3
1914
by: Vijai Kalyan | last post by:
I have been thinking about this and it may have already been thrashed out and hung out to dry as a topic of no more interest but here goes. I found when implementing a smart pointer that the typical implementation goes like: template<typename T> class SmartPointer { // other stuff
10
4135
by: Kieran Simkin | last post by:
Hi, I wonder if anyone can help me, I've been headscratching for a few hours over this. Basically, I've defined a struct called cache_object: struct cache_object { char hostname; char ipaddr; };
1
1790
by: mrhicks | last post by:
Hello all, I need some advice/help on a particular problem I am having. I have a basic struct called "indv_rpt_rply" that holds information for a particular device in our system which I will call INDV. The struct looks like // Some info used for the struct typedef unsigned char uint8; /* 8 bits */
204
13141
by: Alexei A. Frounze | last post by:
Hi all, I have a question regarding the gcc behavior (gcc version 3.3.4). On the following test program it emits a warning: #include <stdio.h> int aInt2 = {0,1,2,4,9,16}; int aInt3 = {0,1,2,4,9};
8
5158
by: Axter | last post by:
I normally use a program call Doxygen to document my source code.(http://www.stack.nl/~dimitri/doxygen) This method works great for small and medium size projects, and you can get good documentation like the following: http://axter.com/smartptr Now I'm on a client site, and I'm trying to create the same type of documentation on a very large project. I ran the Doxygen program, and it ran for over 16 hours, before I had
59
5150
by: MotoK | last post by:
Hi Experts, I've just joined this group and want to know something: Is there something similar to smart pointers in C or something to prevent memory leakages in C programs. Regards MotoK
156
5914
by: Lame Duck | last post by:
Hi Group! I have a vector<floatvariable that I need to pass to a function, but the function takes a float * arguement. That's OK, I can convert by doing &MyVector.front(), but when I get back a float * from the function, how to convert that back to a vector? Thanks in advance!
14
1991
by: Szabolcs Borsanyi | last post by:
Deal all, The type typedef double ***tmp_tensor3; is meant to represent a three-dimensional array. For some reasons the standard array-of-array-of-array will not work in my case. Can I convert an object of this type to the following type?
0
9711
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9591
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10594
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9166
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6861
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5667
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4306
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3831
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3001
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.