L
L
LNK2016-06-26 20:30:42
Programming
LNK, 2016-06-26 20:30:42

What does this object creation mean: SmartPointer sp?

I am writing code based on a video lesson, a class of smart pointers. I don’t understand what kind of object definition is this: SmartPointer<Foo> sp(new Foo(2,2));what are the <> brackets for?
And yet, how can a pointer be void: std::ptrdiff_t operator -(void *p)is it a reference to nothing?
Please explain the meaning of <> brackets.
Here is the code:

#include <iostream>

template <class Type>

class SmartPointer {
  Type* pointer;
public:
  SmartPointer(Type* p) : pointer(p) {};
  operator Type*() { return pointer; };
  Type *operator->() { 
    if (!pointer) {
      pointer = new Type();
      std::cerr << "Bad Ponter!" << std::endl;
    }
    return pointer; 
  };
  std::ptrdiff_t operator -(SmartPointer<type> p) {
    return pointer - p;
  }
  std::ptrdiff_t operator -(void *p) {
    return pointer - p;
  }
};

class Foo {
  int a, b;
public:
  Foo() : a(0), b(0) {};
  Foo(int a, int b) : a(a), b(b) {};
  int sum() { return a + b; }

};

int main(int argc, char **argv) {
  SmartPointer<Foo> sp(new Foo(2,2));
  std::cout << sp->sum() << std::endl;
  system("pause>>void");
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
Rou1997, 2016-06-26
@NikHaker

There are types (classes) - "generics", their functionality depends on the type of the template, for example class Array<T>, where T is some type, say, Array<int>it will be an array of ints, Array<std::string>- an array of std::strings, etc. ., in this case the class SmartPointer<Foo> sp;implements a "smart pointer" of the formFoo* sp;
void* is a "universal" pointer type, you can cast a pointer of any type to it, as well as to int, where int will contain a number - the address (cell number) in memory where the data you point to is contained.

M
Maxim Moseychuk, 2016-06-26
@fshp

Template parameters are specified in angle brackets.
Templates are described from the first pages of any book for dummies.

D
Daniil Igorevich, 2016-06-26
@Petr_Anisimov

Smart pointers are made with template classes, so read what templates are: microsin.net/programming/pc/an-idiots-guide-to-cpp...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question