Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
295 views
in Technique[技术] by (71.8m points)

c++ - Assign to array that can allow NULL members, without using the heap?

Are there any simple, effective answers to this?... aside from, "Decide which is more important", that is.

Let me elaborate. I want a fixed size array. It represents session slots that can be opened for a socket server to accept clients. There are a limited number of these (four, at present).

Perhaps from a C++ perspective my question is all wrong. Perhaps I should be considering these as session slots which, while filled with session objects, may not necessarily be usable until a given session has a reference to a connected TCP socket. This differs from most dynamic languages where I could simply specify the session slots as null until such time as a session fills that slot in the array.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you want an object with automatic storage that has optional semantics (i.e. may or may not exist), you can use boost::optional.

boost::optional<T> is a container that can have zero or one elements. If it is empty, it doesn't store a T object, just like an empty vector doesn't store any object. In fact, you can think of boost::optional<T> as as std::vector<T> whose capacity is always 1 and cannot grow. And since the storage size required for this is fixed and known at compile-time (it's sizeof(T)), boost::optional doesn't need any dynamic allocation.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...