Skip to content

Instantly share code, notes, and snippets.

@MartinNowak
Last active October 23, 2017 19:59
Show Gist options
  • Save MartinNowak/b406a6b7aa6d0964147c107771b64333 to your computer and use it in GitHub Desktop.
Save MartinNowak/b406a6b7aa6d0964147c107771b64333 to your computer and use it in GitHub Desktop.
@safe, scope, and RC related question marks
//==============================================================================
//
struct String
{
/// clone string, doesn't escape, but return value must have independent lifetime
String clone() scope
{
return String();
}
}
unittest
{
static String bug(scope String s)
{
return s.clone;
}
String s;
String s2 = bug(s);
}
//==============================================================================
// https://forum.dlang.org/post/vgazhxutaxbvqgmqtkbt@forum.dlang.org
struct IOPipe
{
ubyte[] window()
{
return ptr[beg .. end];
}
void extend(size_t n)
{
ptr = .realloc(ptr, end - beg - n);
}
}
void use()
{
IOPipe pipe;
auto w = pipe.window;
pipe.extend(100); // window invalidates (similar to iterator invalidation)
w[0];
}
//==============================================================================
void assign(scope ref int* a, scope ref int* b)
{
b = a; // scope variable a assigned to b with longer lifetime
}
void copyScopePtr() @safe
{
int var;
scope int* p1 = &var;
int* p2;
// p2 = p1; // will correctly infer p2 as scope
assign(p1, p2); // function itself doesn't compile
return p2;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment