Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need explanation for C++ code

Tags:

c++

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.

like image 568
wajed Avatar asked Dec 16 '22 13:12

wajed


1 Answers

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.

like image 190
Johannes Schaub - litb Avatar answered Jan 04 '23 06:01

Johannes Schaub - litb