0

What will happen with reference counting in the following code for php7? In php7 zvals are created on stack, so the reference issues arise:

zval destination;
array_init(destination);

{
    // scope begin

    zval val;

    // does val's refcount incremented here or val is copied?
    add_next_index_zval(destination, val);

    // here the "val" will be destroyed.
    // Does "destination" will experience any problems?
}
Machavity
  • 30,841
  • 27
  • 92
  • 100
pavelkolodin
  • 2,859
  • 3
  • 31
  • 74
  • 1
    Hard to say without more specific code, but generally this is fine. The value of `val` is copied into the array, so if the `val` variable goes out of scope that does not matter. – NikiC Jul 14 '16 at 13:22

2 Answers2

0

I believe it is copied. If you use the zval here to hold a custom class instance, you'll need a copy constructor for your class to compile this code.

I think that automatic RC happens when you program in PHP not C. You have to use pointers to take advantage of reference in this level.

And if you explore more about writing PHP extensions, you'll find that actually Zend Engine asks you how you would like to do with RC and the original (objective) zval while returning it back to PHP (the second and third parameter of RETURN_ZVAL()). If you don't deal with them carefully, there may be memory leakage (in debug mode ZE will tell you this!) or even segfault.

Frederick Zhang
  • 3,593
  • 4
  • 32
  • 54
0

In PHP 7, zvals aren't referenced, only their values.

If the zval contains a non-refcounted type (null, booleans, integers, floats), then PHP will simply copy the zval.

If the zval contains a refcounted type (strings, arrays, objects, resources and references), then PHP will copy the zval and increment the reference count of the value (e.g. zend_string or zend_array) the zval points to. The zval itself doesn't have a refcount.

Andrea
  • 19,134
  • 4
  • 43
  • 65