Prevent inheritance of new operator and remove

(I looked, but could not find anything like it; if you cheat, please close it).

Is there a way to prevent the inheritance of these two statements? For instance:

struct foo{
  static void* operator new(std::size_t) { 
    // special
  }
  static void operator delete(void* p, std::size_t) { 
    // special
  }
};    

struct bar : public foo {
};

Now barinherits two operators - in this trivial case is not such a big problem, a problem arises if foo, and barhave data members (and, worse, as a distribution to fooneed to do differently with bar!) Is now a way to avoid this is which in bari would also implement the operators. However, if there are many derived types, the likelihood that you forget to override something is quite possible. So the question is, is there a way to prevent the inheritance of these operators?

: ++ 03 ( - , gcc)

+5
6

foo, / .

class foo_without_new : public foo
{
protected: 
 foo_without_new(){} // only derived types should be able to construct foo_without_new!
public:    
 void *operator new(size_t sz) 
 { 
     return ::operator new(sz);
 }
 void operator delete(void*p) 
 { 
     return ::operator delete(p);
 }
}; 

class Bar : public FooWithoutNew
{
};

- , , .

+3

: !

struct Foo
{
  static void * operator new(std::size_t n)
  {
    if (n != sizeof(Foo))  // subsumes check for n == 0
    {
      return ::operator new(n);
    }
    // your code here
  }
}

, . , .. , , , , , - .

, , - .

+3

, - , ?

+1

new delete - - - .

, , , Base::operator new , , .

#include <iostream>

struct Base {
    int x;
    void * operator new (unsigned int s) {
        std :: cout << "Base\n";
        return :: operator new (s);
    }
};

struct Derived : public Base {
};

int main () {
    new Base ();
    new Derived ();
}

// Prints "Base\nBase\n"

,

  • ,
  • operator new.

, , . "" , - . GOTW, .

+1

, . bar foo. bar?

struct foo{
    static void* operator new(size_t) { 
       // special
    }

    static void operator delete(void* p, size_t) { 
       // special
    }
};    

struct bar : public foo {
    static void* operator new(size_t s) { 
       return ::operator new (s);
    }

    static void operator delete(void* p, size_t s) { 
       ::operator delete (p);
    }
};

. :

bar * pbar = new bar(); // this is ok
foo * phaha = pbar;
delete phaha;           // this is not (foo:operator delete(void*, size_t) is called)
0

, foo

, . new/delete static ; , . . , .

. , , - new delete. .

  struct foo;
  template<typename T>
  T* New { return ::operator new T; }
  template<>
  foo* New<foo> { return new foo; }

  struct foo{
  template<class T> friend T* New();
  private:
  static void* operator new(size_t) { 
     // special
  }
};

- . , new New<foo>() New<bar>(); new. delete.

0

All Articles