简体   繁体   中英

C++ typedef in a class

I use this C++ code for storing x to the variable val.

class Hello
{
  int val;
public:
  Hello(int x) : val(x) {}
};

However, when I saw this code, I cannot see how Super can store value t or o.

template<typename T>
class K : public std::auto_ptr<T>
{
    typedef std::auto_ptr<T> Super;
public:
    K() : Super() { }
    K(T* t) : Super(t) { }
    K(K<T>& o) : Super(o) { }
};

How does this code work?

Could've been written as

template<typename T>
class K : public std::auto_ptr<T>
{
public:
    K() : std::auto_ptr<T>() { }
    K(T* t) : std::auto_ptr<T>(t) { }
    K(K<T>& o) : std::auto_ptr<T>(o) { }
};

Which is just more verbose to initialize the base class. A typedef is cleaner most of the time if you have to deal with templated base classes.

It's because class K inherits from std::auto_ptr<T> . What is happening is that the constructors K(T* t) and K(K<T>& o) call the parent constructor std::auto_ptr<T>(...) , which is also called Super thanks to typedef.

The typedef typedef std::auto_ptr<T> Super; means that Super is an auto_ptr of type T. The empty constructor of K initializes Super, if a pointer of type T is given then Super is initialized to be an auto_ptr managing it, and if a reference to K with type T is given then this is passed to Super.

The auto_ptr<T> base class that you are deriving from is a container for an element of class T . That base class has (at least) the constructors defined that you are calling:

The baseclass could be defined like this (actually, it is not, but this constructor-definitions might give you a picture):

template<typename T>
class auto_ptr {
    T* value;
  public:
    auto_ptr() : value(NULL) {}
    auto_ptr(T* t) : value(t) { }
    auto_ptr(auto_ptr<T>& other) : value(other.value) {}
};

So, auto_ptr<T> holds a value of type T . And the three defined constructors take care of:

  • empty/standard constrcution
  • construction from a raw pointer
  • copy of the container

So, and then by telling in you class, that you give Super the name std::auto_ptr<T> that is just an abbreviation to call the respective base class constructor. You could have written

template<typename T>
class K : public std::auto_ptr<T>
{
public:
    K() : std::auto_ptr<T>() { }
    K(T* t) : std::auto_ptr<T>(t) { }
    K(K<T>& o) : std::auto_ptr<T>(o) { }
};

because you are now directly calling the base class constructors. And those we have defined before (and in "real life" are defined with more sense then I did here).

PS: auto_ptr<> is nice as long as you have not seen unique_ptr<> . auto_ptr<> s "bad guy" is it's copy-constructor. Watch out for C++0x...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM