简体   繁体   中英

c++ const char * assigment operator overload

How to deal with const char * ?

Obj(const Obj& o); // <--
Obj& operator=(const Obj& o);// <-- How to do it right?

// Obj(const Obj& o); // <--
// Obj& operator=(const Obj& o);

class Obj
{
protected:
  const char * name;
  const char * desc;
public:
  Obj(const char * _name,
      const char * _desc)
  :name(_name)
  ,desc(_desc)
  {
    //
  }

  Obj(const Obj& o); // <--
  Obj& operator=(const Obj& o);// <-- Have no idea how to implement this...

  virtual ~Obj(){}
};

class B:public Obj
{
    float v1, v2;
    B(float a, float b)
    :v1(a)
    ,v2(h)
    ,Obj("B","class")
    {
      //
    }

};

Update

T& operator=(const T& other)            // copy assignment
{
  if (this != &other)
  { // self-assignment check expected
    if (other.size != size)
    {                                   // storage cannot be reused
        delete[] mArray;                // destroy storage in this
        size = 0;
        mArray = nullptr;               // preserve invariants in case next line throws
        mArray = new int[other.size];   // create storage in this
        size = other.size;
    }
    std::copy(other.mArray, other.mArray + other.size, mArray);
  }
  return *this;
}

Edit: your code has a serious bug in the form of Obj("B","class") , it assings to the members external pointers rather than copying their data. Forget all about it, including my answer, and use std::string .

Copying objects with pointers means that you want to serialize the pointer data. In case it's a string, a strcpy/memcpy would suffice:

Obj& operator=(const Obj& o)
{ 
name = new char[o.namesize + 1]; // must keep the size unless it's a string, so you can assume the size with strlen().
strcpy_s(name,o.namesize + 1,o.name); 
namesize = o.namesize;


 // With strlen
 name = new char[strlen(o.name) + 1];
 strcpy_s(name,strlen(o.name) + 1,o.name);

return *this;
}

However, always use std::string and forget about all this stuff since it will be handled automatically by STL, including move semantics, automatic memory management etc.

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