473,796 Members | 2,599 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 #1
12 5223
Henrik Goldman wrote:
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
What is wrong with std::vector ?
Dec 26 '06 #2
>
What is wrong with std::vector ?
I forgot to mention that it's a requirement that the data needs to be
accessible from external C functions. For this reason it needs to be
serialized just like an ordinary array.

-- Henrik
Dec 26 '06 #3
"Henrik Goldman" <he************ @mail.tele.dkwr ote in message
news:45******** *************@d read11.news.tel e.dk...

What is wrong with std::vector ?

I forgot to mention that it's a requirement that the data needs to be
accessible from external C functions. For this reason it needs to be
serialized just like an ordinary array.

-- Henrik
std::vector fits the bill for that.
http://www.parashift.com/c++-faq-lit....html#faq-34.3
vector stores it's memory contiguous

Dec 26 '06 #4

Henrik Goldman wrote:

What is wrong with std::vector ?

I forgot to mention that it's a requirement that the data needs to be
accessible from external C functions. For this reason it needs to be
serialized just like an ordinary array.

-- Henrik
The std::vector is then perfect for the job. Not only are its elements
organized in contiguous memory and dynamic, its also much easier to
overload a global op<< to stream/serialize the data.

Show me code with a primitive array, and i'll show you a std::vector
that does the same but better, and then some. And that includes
performance.

Dec 26 '06 #5
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. All in all it does
save me from some work so it's a cheap price to pay.

-- Henrik
Dec 26 '06 #6

Henrik Goldman wrote in message
<45************ *********@dread 11.news.tele.dk >...
>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(nElem ents);
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. All in all it does
save me from some work so it's a cheap price to pay.
--- Henrik
std::size_t nElements( 100 );
std::vector <mytypev( nElements, mytype(0) );

--
Bob R
POVrookie
Dec 26 '06 #7

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. All in all it does
save me from some work so it's a cheap price to pay.

-- Henrik
Oh yes you can. In more ways than one.
There is no need to use memset, let a ctor and copy-ctor do the work
for you.

#include <vector>

template< typename T >
class mytype
{
T t;
public:
mytype() : t() { }
mytype(const T& r_t) : t(r_t) { }
};

int main()
{
std::vector< mytype< double instance(1000); // same as
instance(1000, 0.0);
std::vector< mytype< double another(1000, 11.1);
std::vector< std::string vstrings(1000, "default string");
std::vector< int vn(1000, 99);
}

The first creates an instance of a std::vector with 1000 elements all
initialized to 0.0 (by def ctor)
The second initializes 1000 elements with a value of 11.1 (using
parametized ctor)
The third initializes 1000 std::strings with the same default.
The fourth has 1000 integers set to 99.

The only requirement is that the element-type be copyable and
assignable (op=). In the case involving the class above, mytype's
compiler-generated copy ctor and assignment operator fits the bill. In
the event your class doesn't have a compiler-generated ctor or op=,
make them.

Dec 26 '06 #8
Henrik Goldman wrote:
>What is wrong with std::vector ?

I forgot to mention that it's a requirement that the data needs to be
accessible from external C functions. For this reason it needs to be
serialized just like an ordinary array.
Again, what's wrong with std::vector? :)

std::vector<Tve c = ...;

extern "C" T *GetCArray()
{
return &vec.front() ;
}

--
Clark S. Cox III
cl*******@gmail .com
Dec 27 '06 #9

Henrik Goldman wrote:
>
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. All in all it does
save me from some work so it's a cheap price to pay.
If mytype is a class then its constructor will automatically be called.

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.

Note that you could use a "static" instance of one.

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.

Dec 27 '06 #10

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

Similar topics

9
2156
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
4133
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
1788
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
13128
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
5156
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
5147
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
5911
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
1989
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
9673
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
10449
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...
1
10168
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10003
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9047
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...
1
7546
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6785
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
5440
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5568
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.