How to write Template class copy constructor

喜你入骨 提交于 2019-12-04 06:41:19

Assuming _TyV is a value type:

Vertex( Vertex const& src )
    : m_Label( src.m_Label )
{}

Aren't those names within class instances reserved by the implementation, by the way?

The C++ standard reserves a set of names for use by C++ implementation and standard libraries [C++ standard 17.6.3.3 - Reserved names]. Those include but are not limited to:

  • Names containing a double underscore.
  • Names that begin with an underscore followed by an uppercase letter.
  • Names that begin with an underscore at the global namespace.

Either a) not at all, just rely on the compiler-provided default; or b) by just invoking the copy constructor of the member:

template <typename T> struct Foo
{
  T var;
  Foo(const Foo & rhs) : var(rhs.var) { }
};

The point is of course that the compiler-provided default copy constructor does precisely the same thing: it invokes the copy constructor of each member one by one. So for a class that's composed of clever member objects, the default copy constructor should be the best possible.

Nawaz
template <typename T>
class Vertex {
public:

    //this is copy-constructor
    Vertex(const Vertex<T> &other) 
          : m_Color(other.m_Color),m_Label(other.m_Label)
    {
      //..
    }
    //..
};

But I don't think you need to explicitly define the copy-constructor, unless the class have pointer member data and you want to make deep-copy of the objects. If you don't have pointer member data, then the default copy-constructor generated by the compiler would be enough.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!