Is this destructor valid in C ++?

  • String::~String() { std::cout<<"String()" <<std::endl; }

    I wonder if this implementation of the destructor is valid?

  • And one more question about the const member function specifier, I know that the const function cannot change variables in this class, it is just read-only. If there are no other weird questions about this, I think I can figure it out, but I saw a few questions:

    • It allows you to call the function of a non-constant member for the object pointed to by this

    • This ensures that only the mutable member variables of the object it points to can be changed

    • This ensures that all constants remain unchanged.

    • It prevents inheritance

    • It allows you to change the state of the object that this

Based on my understanding, it is very difficult to verify which one is right, so I think they are all wrong?

+3
source share
4 answers
  • The destructor is technically just another function, for me this destructor does not seem to be syntactically syntactic, so it seems to be valid

  • This is all there is for constant member functions; you cannot modify data. These functions are automatically called by an instance of the const class. Therefore, if you have two functions with the same signature, except for a constant, it will choose the version of const for instances of const, and for non-const instances it will depend on how you use it, which determines which version is called

    a) you cannot call non-const member functions inside a const member function

    b) right

    c)

    d) , , . , const ,

    e) , const, mutable.

+4

, ?

. , , ? , ; , , . , , . " ", , " ".

+3

, .

const . .

, .

C++ FAQS.

+3

2.

- cv 'this'.

, ++ C:

class A
{
public:
  void f1 ();
  void f2 () const;

private:
  int i;
};

, C:

struct A
{
  int i;
};

void f1 (A * const this);        // Non const member
void f2 (A const * const this);  // Const member

, , , , , (*this). :

void A::f1 ()
{
  i = 0;         // This and the next line have the same meaning
  (*this).i = 0;
}

- const, this const:

void A::f2 () const
{
  (*this).i = 0;  // Error '*this' is const, so cannot modify (*this).i
}

-, , , const , . :

class A
{
public:
  void f () const
  {
    *i = 0;
  }

private:
  int * i;
};

It doesn’t look right, but it’s actually normal. (*this).iis a constant, so you cannot change what it points to i, but iit is still a pointer to non const int, so we can change the value that it points to i.

0
source

All Articles