定位new表达式与显式调用析构函数

C++的核心理念之一是RAII,Resource Acquisition Is Initialization,资源获取即初始化。资源有不少种,内存、互斥锁、文件、套接字等;RAII能够用来实现一种与做用域绑定的资源管理方法(如std::lock_guard);这些都不在本文的讨论范围以内。ios

内存是一种资源。从字面上来看,“资源获取”是指在栈或堆上开辟空间,“初始化”是指调用构造函数,“即”的意思是二者是绑定起来的。对应地,资源销毁即释放。这种机制保证了任何函数访问参数对象时不会访问到非法地址,除了构造和析构函数之外的任何函数的参数都不会是未初始化的。数组

然而,C++做为可以面向底层的语言,容许咱们把内存获取与初始化分开来:std::mallocstd::free用于分配和释放内存,定位new表达式和析构函数的显式调用用于初始化和销毁对象。函数

malloc与free

std::malloc用于分配内存,std::free用于释放内存,二者都定义在<cstdlib>中:测试

void* malloc(std::size_t size);
void free(void* ptr);

好比,我想要分配一个int的动态内存,就应该给size填上sizeof(int),返回值就是指向那个int的指针。若是是数组,就给size乘上元素个数。注意在C++中,从void*T*的转换不能是隐式的。ui

要回收它,把指针传给free,不须要sizethis

#include <iostream>
#include <cstdlib>

int main()
{
    auto p = static_cast<int*>(std::malloc(sizeof(int) * 10));
    p[0] = 1;
    p[1] = 2;
    std::cout << p[0] << ' ' << p[1] << std::endl;
    std::free(p);
}

若是std::malloc过程当中发生了错误,好比内存不足,std::malloc会返回NULLnullptr的前身。实际使用时都应该考虑这种状况。指针

std::malloc获得的内存必须用free释放。std::malloc/std::free的内存分配与new/delete不互通。code

定位new表达式

std::malloc分配的内存是未经初始化的,对于int等内置类型能够直接使用,而类类型则未必,须要先初始化才能使用。对象

咱们知道,类的非静态成员函数都有一个隐式的this指针做为参数,构造函数也不例外,在未初始化的内存上构造对象,就是把这块内存的指针做为this传入构造函数。不幸的是,没有显式调用构造函数这种语法:内存

auto ptr = static_cast<A*>(std::malloc(sizeof(A)));
ptr->A("hello"); // error

(在MSVC中,ptr->A::A("hello");是合法的,但这是非标准的。)

咱们须要定位new,它定义在<new>中,须要#include之后才能使用:

void* operator new(std::size_t, void*);

new运算符是能够重载的,new运算符的功能是为new表达式中的构造函数提供this指针。可是定位new不行,它老是忠实地返回它的第二个参数。

定位new表达式有如下形式:

new (ptr) Type;
new (ptr) Type(args);
new (ptr) Type[size];
new (ptr) Type[size]{list};

ptr为要看成this的指针,Type为要构造的类型,args为可能为空的参数列表,size为数组大小(能够动态),list为数组元素列表。

利用定位new,把ptr做为this的构造函数能够这样调用:

#include <iostream>
#include <cstdlib>
#include <string>
#include <utility>

class A
{
public:
    A(std::string s) : string(std::move(s))
    {
        std::cout << "A::A(std::string)" << std::endl;
    }
    std::string& get()
    {
        return string;
    }
private:
    std::string string;
};

int main()
{
    auto ptr = static_cast<A*>(std::malloc(sizeof(A)));
//  std::cout << ptr->get() << std::endl; // disaster
//  ptr->A("hello");                      // error
    new (ptr) A("hello");
    std::cout << ptr->get() << std::endl;
//  delete ptr;                           // disaster
    // what's next?
}

不要由于ptr简单就不加括号,括号不是为了什么运算符优先级,而是定位new表达式的一部分。

刚才不是说std::mallocnew不互通吗?怎么在std::malloc来的ptr上用定位new了呢?由于定位new根本不插手内存分配,和std::malloc是两回事。

定位new不止能够用于std::malloc来的动态内存,甚至能够是局部变量:

char buffer[sizeof(A)];
auto ptr = new (buffer) A("hello");
std::cout << ptr->get() << std::endl;

与常规的new同样,定位new表达式也返回一个指针,就是Type*类型的ptr

显式调用析构函数

上面经过std::malloc获得的ptr,为何不能直接std::free呢?由于std::string里面的资源还没释放,正确的作法是调用A的析构函数。

不能对一个对象调用构造函数,那么析构函数呢?答案是确定的。只是~在形式上有点怪,尤为是当你把模板参数T换成int后获得ptr->~int()时,后者直接写是不合法的。

因此对于上面的ptr,要这样才能释放全部资源:

ptr->~A();
std::free(ptr);

显式调用析构函数,就像在帮编译器作事情同样。编译器会不会领情呢?写个代码测试一下吧:

#include <iostream>
#include <string>
#include <utility>

class A
{
public:
    A(std::string s) : string(std::move(s))
    {
        std::cout << "A::A(std::string)" << std::endl;
    }
    std::string& get()
    {
        std::cout << "A::get()" << std::endl;
        return string;
    }
    ~A()
    {
        std::cout << "A::~A()" << std::endl;
    }
private:
    std::string string;
};

int main()
{
    {
        A a("");
        a.~A();
    }
    std::cout << "I'm OK" << std::endl;
}

程序输出:

A::A(std::string)
A::~A()
A::~A()
I'm OK

看来编译器并不领情,即便咱们调用了析构函数,变量离开做用域时还会再调用一次。尽管在MSVC和GCC中,I'm OK都成功输出了,std::string都挺住了错误的析构,可是这个程序的行为仍然是未定义的。

所以,定位new语句与析构函数的显式调用必须配对。

相关文章
相关标签/搜索