Why is it allowed to write Test object(); Test object{};
in case of deleted constructors?
When you write
Test object();
it doesn't mean that you create class object in case of deleted constructor, compiler understood a function, thats why when you try to writestd::cout << sizeof(object)
you will get error:ISO C++ forbids applying sizeof to an expression of function type
. I can understand that it is not deprecated for backwards compatibility, but it could be optimized and fixed in C++11 which is not done.Started from C++11, you can create object with
Test object3{};
syntax, which is already valid object even though deleted constructor, and when you dostd::cout << sizeof(object3)
the output is1
. In this case it means that operatordelete
is useless.The same about writing it inprivate
section in old versions.You can use this style of code when you want to create an aggregation of functions and to have encapsulation. So please don't write in answers for example
Why do you use class instead of namespace
, etc...
class Test {
Test() = delete;
Test(const Test&) = delete;
Test(Test&&) = delete;
Test& operator=(const Test&) = delete;
public:
template<typename T>
static void func();
private:
static std::string m_fileName;
};
int main() {
Test object(); //Compiles as function returning Test object
Test object2; //Doesn't compile because of deleted constructor
Test object3{}; //Compiles and it creates an object even though deleted constructor
Test object4({}); //Doesn't compile because of deleted constructor
return 0;
}