gpt4 book ai didi

c++ - 公共(public)新私有(private)构造函数

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:54:08 26 4
gpt4 key购买 nike

当我尝试编译以下内容时:

#include <iostream>

class Test
{
public:
void* operator new (size_t num);
void operator delete (void* test);
~Test();
private:
Test();
};

Test::Test()
{
std::cout << "Constructing Test" << std::endl;
}

Test::~Test()
{
std::cout << "Destroying Test" << std::endl;
}

void* Test::operator new (size_t num)
{
::new Test;
}

void Test::operator delete(void* test)
{
::delete(static_cast<Test*>(test));
}

int main()
{
Test* test = new Test;
delete test;
}

我明白了:

$ g++ -o test test.cpp
test.cpp: In function ‘int main()’:
test.cpp:14: error: ‘Test::Test()’ is private
test.cpp:36: error: within this context

如果new是成员函数,为什么不能调用私有(private)构造函数?

编辑:我的想法是创建一个只能使用完全标准语法在堆上实例化的类。我希望因为 new 是一个数据成员,它可以调用私有(private)构造函数,但由于 new 不用于堆栈对象,因此您将不能在堆栈上创建对象。

最佳答案

我认为您对 operator new 的作用有误解。它不创建对象,而是为对象分配内存。编译器将在调用您的 operator new 后立即调用构造函数。

struct test {
void * operator new( std::size_t size );
};
int main()
{
test *p = new test;
// compiler will translate this into:
//
// test *p = test::operator new( sizeof(test) );
// new (static_cast<void*>(p)) test() !!! the constructor is private in this scope
}

operator new 的主要用途是拥有一个不同于系统默认分配器(通常是 malloc)的内存分配器,它旨在返回一个未初始化的内存区域,编译器将在该区域调用构造函数。但是在写入新调用的范围(在本例中为 main)中分配内存后, 调用了构造函数。

接受通知后

未制定问题的完整解决方案:我如何强制我的类的用户在堆中实例化? 是使构造函数私有(private)并提供工厂函数,如其他一些答案所示(如 villintehaspam 的那个)指出。

关于c++ - 公共(public)新私有(private)构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2178760/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com