operator new & delete overriding in template

C

Cheng Mo

When overriding operator new & delte of one class, the method is
implicitly declared as static. However, overriding operator new & delete
of template cannot be static.The compiler says cannot declare the
function a static linkage. Why?
C++ is so complex and so many situation should be considered.
 
V

Victor Bazarov

Cheng Mo said:
When overriding operator new & delte of one class, the method is
implicitly declared as static. However, overriding operator new & delete
of template cannot be static.The compiler says cannot declare the function
a static linkage. Why?
C++ is so complex and so many situation should be considered.

Read the FAQ 5.8.

This:
--------------------
#include <typeinfo>
#include <iostream>

template<class T>
class A {
public:
A(int) {}
void * operator new(size_t s) {
std::cout << "new A<" << typeid(T).name() << ">\n";
return malloc(s); }
void operator delete(void* p, size_t s) { free(p); }
};

int main()
{
A<int> *paint = new A<int>(42);
}
 
C

Cheng Mo

I know that the compilation and execution is OK.
What I want to konw is that why member functions in template cannot be
declared as static.
 
V

Victor Bazarov

Cheng said:
I know that the compilation and execution is OK.
What I want to konw is that why member functions in template cannot be
declared as static.

I don't understand the question, probably. Overloaded operators 'new' and
'delete' shall not be _declared_ static, but they _are_ static, as you
noted in your post. Any other function _can_ be declared static, unless
it's a constructor, the destructor, operator= (and some other operators).

What makes you think that members of templates can't be static?

template<class T> class HasStatic {
public:
static void foo(); // here it is, a static member
};

And, please, don't top-post, OK? Thanks!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top