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

牧云@^-^@ 提交于 2019-12-13 09:22:44

问题


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.


回答1:


There's nothing preventing you from still using pointers. Pointers can point to any non-temporary objects, including ones that live on the stack.

Example:

void func()
{
    MyObject obj;
    MyObject* p = 0;

    if(some_condition)
        p = &obj;

    ...
}



回答2:


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.




回答3:


speculating on tenfour's answer, this code would work, and is actually common:

bool function(int parameter, TYPE& return_val) {
    if (parameter > 7) {
        return_val = 7;
        return true;
    }
    return false;
}

It's not a pointer, but it's simple. pass the return by reference, and if you assigned it a value, return true. Otherwise, return false.



来源:https://stackoverflow.com/questions/8493660/assign-to-array-that-can-allow-null-members-without-using-the-heap

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!