namespace Stack {
struct Rep; // definition of stack layout is elsewhere
typedef Rep& stack;
stack create(); // make a new stack
void destroy(stack s); // delete s
void push(stack s, char c); // push c onto s
char pop(stack s); // pop s
}
This is in the "A Tour of C++" Unit, before even the basic material like functions, loops, and fundamental datatypes...I don't know if/how I'm supposed to understand this code or not.
Anyway, can someone please explain it? It's supposed to be part of an explanation on how to "define a stack manager with an interface"
For starters, I specifically don't know what "typedef Rep& stack
" means.
In short, stack
is a typedef for a reference to the type Rep
. That means, whenever you use stack
, you denote the type "reference to Rep".
In my opinion, this is a weird C++ course material. From what the interface looks like, we can suppose the implementation will be something like
/* in darkcorner.cpp: */
stack create() { // make a new stack
stack s = *new Rep;
return s;
}
void destroy(stack s) { // delete s
delete &s;
}
void push(stack s, char c) { // push c onto s
s.push(c);
}
char pop(stack s) { // pop s
return s.pop();
}
Now, if you do the following, you violate the principle of least surprise for most C++ programmers.
stack p = create();
stack p2 = p;
The "principle of least surprise" says that this shall copy the stack. But actually, stack
stands for the type Rep&
, which is a "reference to Rep". This means that the second line creates an alias to p
(reference to what p
refers to). It doesn't copy, but just creates another reference.
I recommend you: Stay clear of such code. If you want to hide the implementation or layout of Rep
, then implement the Pimpl idiom.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With