nitializing a static vector <> of integers (this static vector<int> is a class member)

  • Follow


I have recently (today) subscribed to your mailing list and I would
like to see if you can assist me in a technical roadblock regarding
std::vector<> initialization within a class (but the vector is static).

I have looked at C++ PL Special Edition, your  Effective  C++ series,
Lippman's  C++ Primer  (3rd Edition) and the web and I have not seen a
good (working) snippet of C++ code to perform the following:


I have the following class (interface):

class SignalHandlerBase
{
  public:

    virtual ~SignalHandlerBase ();
    virtual int handleSignal (int signal, siginfo_t* info = 0, void*
context = 0) = 0;
};

Then I have another class (like above details for POSIX signals not
important) named SignalHandler.

class SignalHandler
{
  pubic:
   //ctor
    SignalHandler ();
   //dtor
    ~SignalHandler ();

  //Remaining member function declarations omitted for brevity
  ...
   private:

    static SignalHandlerBase *signal_handlers_ [NSIG];
};

Scott here is I am stuck.

First of NSIG is defined to be 31 in signal.h or csignal (for C++) .

I would like to use STL vector instead of a C-style array here:

How would I syntantically replace the above version?

Is this correct:

1. std::vector<static SignalHandlerBase*> signal_handlers_;  ? (this
one)

or

2. static std::vector<SignalHandlerBase*> signal_handlers_;  ? (this
one)

now if it is either 1 or 2 how can I initialize this vector to hold no
more than 31 SignalHandlerBase* slots in memory?

Do I in the encapsulating class constructor call
std::vector<T>::reserve (31),


since I cannot do the following:


//As before
class SignalHandler
{
  pubic:
   //ctor
    SignalHandler ();
   //dtor
    ~SignalHandler ();

  //Remaining member function declarations omitted for brevity
  ...
   private:

   std::vector<static SignalHandlerBase*> signal_handlers_ (31);
   //Is it possible to have a vector of static pointer variables?

or

   static std::vector<SignalHandlerBase*> signal_handlers_ (31);
   //Or is it possible to have a static vector of non-static pointer
variables?

};

Which of the above is syntactically correct and the correct replacement
for the C-style array declared further up? Based on the correct version
can you show me how to initialize this correct vector replacement BUT
enforcing that the vector can ONLY hold NO MORE than 31 integers
(signals)?

This would be a great help if you can answer this question.

sample code please:


Much help and your help would be greatly appreciated. I certainly do
not mean to take away from your busy time schedule.



Last item:

I read your item in Effective STL about knowing how to pass vector data
and string data to C APIs. I think this is the best item in the book.

I deal alot with Sockets code and  have seen a great deal of 3rd party
C++ OS Wrapper Facades for Sockets (ACE, Boost, Common++ etc) they all
seem to have wrapper methods that look like this:

ssize_t send (char buffer [], size_t nbytes);

or

char* find (char pathname []) or char* find (const char pathname [])
where char*  or const char* are syntactically replaced with the []
(array versions).

So for:

ssize_t send (char buffer [], size_t nbytes);

can I do this?

ssize_t send (std::vector<char> buffer, size_t nbytes);   ?

The above send () call can then call the BSD Sockets ::send call as
follows:

ssize_t NAMESPACE::send (std::vector<char> buffer, size_t nbytes)
{
  //delegate to the actual OS Library System call
  return ::send (&buffer[0], buffer.size ());
}


I find std::string limiting because I would eventuall call
std::string::c_str () to get the underlying C-style const string which
cannot be passed to API libraries expecting char* - I get the illegal
'error when convering const char* to char*'

It seems that std::vector<char> is more versatile for than std::string
since it can produce a pointer to char (char*) or be casted to const
char*.

std::strings when ::c_str ()'d only produce the const char*.




Thank you,

Tom Wallick


      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Reply tomwallick (2) 2/6/2006 10:14:43 AM

[I'm not Scott, but I'm accessing this newsgroup right now :-)]

"tomwallick@yahoo.com" <tomwallick@yahoo.com> writes:

> I have recently (today) subscribed to your mailing list and I would
> like to see if you can assist me in a technical roadblock regarding
> std::vector<> initialization within a class (but the vector is
> static).

This is a newsgroup, not a mailing list.


> I have looked at C++ PL Special Edition, your Effective C++ series,
> Lippman's C++ Primer (3rd Edition) and the web and I have not seen a
> good (working) snippet of C++ code to perform the following:
>
>
> I have the following class (interface):
>
> class SignalHandlerBase
> {
>   public:
>
>     virtual ~SignalHandlerBase ();
>     virtual int handleSignal (int signal, siginfo_t* info = 0, void*
> context = 0) = 0;
> };
>
> Then I have another class (like above details for POSIX signals not
> important) named SignalHandler.
>
> class SignalHandler
> {
>   pubic:
>    //ctor
>     SignalHandler ();
>    //dtor
>     ~SignalHandler ();
>
>   //Remaining member function declarations omitted for brevity
>   ...
>    private:
>
>     static SignalHandlerBase *signal_handlers_ [NSIG];
> };
>
> Scott here is I am stuck.
>
> First of NSIG is defined to be 31 in signal.h or csignal (for C++) .
>
> I would like to use STL vector instead of a C-style array here:

Why?


> How would I syntantically replace the above version?
>
> Is this correct:
>
> 1. std::vector<static SignalHandlerBase*> signal_handlers_; ? (this
> one)

No. The "static" in the above declaration refers to signal_handlers_,
not to SignalHandlerBase or SignalHandlerBase *.



> or
>
> 2. static std::vector<SignalHandlerBase*> signal_handlers_; ? (this
> one)

This is it.


> now if it is either 1 or 2 how can I initialize this vector to hold
> no more than 31 SignalHandlerBase* slots in memory?
>
> Do I in the encapsulating class constructor call
> std::vector<T>::reserve (31),

Static data member are initialized in their definition, which you have
to add to one translation unit (i.e. a .cpp (or similarly named) file,
not a header file, or the member will probably be defined more than
once).

This definition

std::vector<SignalHandlerBase*> SignalHandler::signal_handlers_;

will cause signal_handlers_ to be initialized with the default
constructor.


To initialize signal_handlers_ to NSIG null pointers, use

std::vector<SignalHandlerBase*> SignalHandler::signal_handlers_(NSIG);


There is now way to restrict an instance of a class generated from
std::vector (nor any other Standard Library container template) to a
maximal number of elements. What you can do is to wrap the container
into an interface (class, or bunch of functions) that controls the
number of elements.


> //As before
> class SignalHandler
> {
>   pubic:
>    //ctor
>     SignalHandler ();
>    //dtor
>     ~SignalHandler ();
>
>   //Remaining member function declarations omitted for brevity
>   ...
>    private:
>
>    std::vector<static SignalHandlerBase*> signal_handlers_ (31);
>    //Is it possible to have a vector of static pointer variables?

No. And you can't initialize most types of data members (including the
type of signal_handlers_) inside the class definition.


> or
>
>    static std::vector<SignalHandlerBase*> signal_handlers_ (31);
>    //Or is it possible to have a static vector of non-static pointer
> variables?
>
> };
>
> Which of the above is syntactically correct and the correct
> replacement for the C-style array declared further up?

None.


> Last item:

[snip]

Maybe it's just me, but I prefer one thread per topic, each with a
descriptive subject.

      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Reply Thomas 2/6/2006 10:29:25 PM


Well, at the first glance, I would like to first know why do you want
to do it this way.

First, vector is not a C++ replacement for arrays. vector is a STL
container - that provides similar behavior and methods - its a
template! it is a generic way of sharing code (behavior) with type
safety.

Second, templates would be very expensive (time complexity) in your
case - especially if you are dealing with signal handlers and would
like to iterate through the collection. [] operator on vector is
overloaded and is _not_ as simple as C's [] resolution. If you use
e1[e2], in C, it is deferenced as *(e1 + e1). This is the reason why
3[a] is similar to a[3] and is also a legitimate syntax in C.

It is also not guarenteed that vector elements will be stored in
contiguosly in memory. it completely depends on the compiler you are
using. VC++ for example uses one chunk in memory and stores them in
sequence, where as it is not the case on some Unix platforms.

Next question is that In case of your SignalHandler which contains
SignalHandlerBase pointers, are you going to have multiple instances of
SignalHandler objects in your system? If no, then you might want to
consider making it singleton.

For your send() question too - vector is not an array! you cant safely
cast it to char*

Another question: why do you want an array? if you want to have a
signal handler object for a signal, wouldn't hashtable be a more
logical ?


      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Reply ydkulkarni 2/6/2006 11:36:45 PM

<tomwallick@yahoo.com> wrote in message 
news:1139163425.602473.116390@g47g2000cwa.googlegroups.com...

> class SignalHandler
> {
>  pubic:
>   //ctor
>    SignalHandler ();
>   //dtor
>    ~SignalHandler ();
>
>  //Remaining member function declarations omitted for brevity
>  ...
>   private:
>
>    static SignalHandlerBase *signal_handlers_ [NSIG];
> };
>
> Scott here is I am stuck.
>
> First of NSIG is defined to be 31 in signal.h or csignal (for C++) .
>
> I would like to use STL vector instead of a C-style array here:
>
> How would I syntantically replace the above version?

class SignalHandler {
// ...
    static std::vector<SignalHandlerBase*> signal_handlers_;
// ...
};

std::vector<SignalHandlerBase*> signal_handlers_(NSIG);


      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Reply Andrew 2/6/2006 11:38:51 PM

ydkulkarni@gmail.com wrote:
>
> Second, templates would be very expensive (time complexity) in your
> case - especially if you are dealing with signal handlers and would
> like to iterate through the collection. [] operator on vector is
> overloaded and is _not_ as simple as C's [] resolution.
>

No. Accessing a vector is likely to generate practically identical code
to accessing an array. At the very least, access is guaranteed to be
constant time.


>
> It is also not guarenteed that vector elements will be stored in
> contiguosly in memory.
>

No. Elements are stored contiguously in a vector. This is guaranteed by
the Standard.


>
> For your send() question too - vector is not an array! you cant safely
> cast it to char*
>

True, you can't directly cast a vector, but the OP's technique (taking
the address of the first element) is correct.


James


      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Reply James 2/7/2006 11:38:50 AM

ydkulkarni@gmail.com wrote:
> Well, at the first glance, I would like to first know why do
> you want to do it this way.

> First, vector is not a C++ replacement for arrays.

It is in many cases.  C style arrays are seriously broken.
And there are very, very few cases where an std::vector will not
do the job better.

> vector is a STL container - that provides similar behavior and
> methods - its a template! it is a generic way of sharing code
> (behavior) with type safety.

So?

> Second, templates would be very expensive (time complexity) in
> your case - especially if you are dealing with signal handlers
> and would like to iterate through the collection.

What makes you say that?

There are some points you have to watch out for -- it definitly
wouldn't do to change the size of the vector in a signal
handler.  But if I understand correctly, he doesn't want to
change the size of the vector at all, once it has been
constructed.  (In his case, Boost's array might be a better
choice than std::vector.  But there's no fundamental problem
with std::vector here either.)

> [] operator on vector is overloaded and is _not_ as simple as
> C's [] resolution.

In most implementations, it ends up generating exactly the same
code at the machine level.

> If you use e1[e2], in C, it is deferenced as *(e1 + e1).  This
> is the reason why 3[a] is similar to a[3] and is also a
> legitimate syntax in C.

Which is, of course, a major argument in favor of std::vector.

> It is also not guarenteed that vector elements will be stored
> in contiguosly in memory.

Actually, it is.  The original wording in the C++ 98 standard
didn't guarantee this, but apparently, the lack of a guarantee
was an oversight.  At any rate, all known implementations have
always used contiguous memory, the intent of std::vector (e.g.
that operator[] be as fast as possible) can only be met with
contiguous memory, and an update to the standard explicitly
guarantees it.

> It completely depends on the compiler you are using.  VC++ for
> example uses one chunk in memory and stores them in sequence,
> where as it is not the case on some Unix platforms.

Which ones?  The committee searched pretty hard to find one
before making the update, and was unable to come up with one.
And as far as I know, all of the implementers for Unix platforms
are on the committee, and were present during the search.

> Next question is that In case of your SignalHandler which
> contains SignalHandlerBase pointers, are you going to have
> multiple instances of SignalHandler objects in your system?
> If no, then you might want to consider making it singleton.

> For your send() question too - vector is not an array! you
> cant safely cast it to char*

You can't cast it, but you can take the address of its first
element, and pass that to a function expecting a C style array.

> Another question: why do you want an array?  If you want to
> have a signal handler object for a signal, wouldn't hashtable
> be a more logical ?

When the key's are taken from a set of small integers, an array
is logically the equivalent of a hash table with a perfect
hashing function.  In this case, the key's are from a set of
integers in the range [0...NSIG); on my machine, NSIG is 46, an
array of 46 pointers doesn't seem to outrageous to me.

--
James Kanze                                           GABI Software
Conseils en informatique orient�e objet/
                    Beratung in objektorientierter Datenverarbeitung
9 place S�mard, 78210 St.-Cyr-l'�cole, France, +33 (0)1 30 23 00 34


      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Reply kanze 2/7/2006 11:44:17 AM

In article <1139267207.613629.218540@f14g2000cwb.googlegroups.com>, 
ydkulkarni@gmail.com writes
>Well, at the first glance, I would like to first know why do you want
>to do it this way.
>
>First, vector is not a C++ replacement for arrays. vector is a STL
>container - that provides similar behavior and methods - its a
>template! it is a generic way of sharing code (behavior) with type
>safety.

Well most of us believe that std::vector is a replacement for dynamic 
arrays.

>
>Second, templates would be very expensive (time complexity) in your
>case - especially if you are dealing with signal handlers and would
>like to iterate through the collection. [] operator on vector is
>overloaded and is _not_ as simple as C's [] resolution. If you use
>e1[e2], in C, it is deferenced as *(e1 + e1). This is the reason why
>3[a] is similar to a[3] and is also a legitimate syntax in C.
Well I have always found vectors to be pretty good timewise and they 
have many other advantages which save quite a lot of protective coding.

>
>It is also not guarenteed that vector elements will be stored in
>contiguosly in memory. it completely depends on the compiler you are
>using. VC++ for example uses one chunk in memory and stores them in
>sequence, where as it is not the case on some Unix platforms.

Rubbish. It is true that the 1998 version of the C++ Standard does not 
explicitly require that the elements of a vector are contiguous, but the 
current version does and AFAIK there has never been a compiler where 
they were not contiguous. If you know of one please tell us about it 
because when WG21 made the contiguity requirement explicit it was 
unaware of this placing any requirement for action on any implementor.

>
>Next question is that In case of your SignalHandler which contains
>SignalHandlerBase pointers, are you going to have multiple instances of
>SignalHandler objects in your system? If no, then you might want to
>consider making it singleton.
Actually signal handlers do not work well with C++ exceptions and 
generally should be avoided in C++


-- 
Francis Glassborow      ACCU
Author of 'You Can Do It!' see http://www.spellen.org/youcandoit
For project ideas and contributions: http://www.spellen.org/youcandoit/projects


      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Reply Francis 2/7/2006 12:19:01 PM

tomwallick@yahoo.com wrote:
[SNIP]
> Scott here is I am stuck.

Do not take the name of Scott in vain! ;-)  Is that Scott Meyers the 3rd 
(Edition) being divined by zero here? :->

> First of NSIG is defined to be 31 in signal.h or csignal (for C++) .
> 
> I would like to use STL vector instead of a C-style array here:
> 
> How would I syntantically replace the above version?

Well, I would use boost:array instead of an std::vector here.  You do 
not need a dynamic array here (what vector is), and boost::array gives 
you some encapsulation (like you have at()).  I really do not see vector 
buying you anything here.

WW aka Attila

      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Reply Attila 2/8/2006 1:45:12 PM

7 Replies
319 Views

(page loaded in 0.102 seconds)

Similiar Articles:













7/23/2012 5:03:47 PM


Reply: