C++有一个自初始化指针

vla*_*sch 2 c++ pointers

问这么简单的问题我有点尴尬:

cpp中是否有任何指针类初始化自身,nullptr但与基本的c-stylish指针100%兼容?

来写:

extern "C" void someFunction(const Struct* i_s);

std::ptr<Struct> p;
// ...
p = new Struct;
// ...
someFunction(p);
Run Code Online (Sandbox Code Playgroud)

有这样的事吗?或者也许在boost或Qt?

编辑:说清楚:我没有搜索获取指针所有权的智能指针并进行重新计数.

vso*_*tco 5

您可以使用以下语法

std::unique_ptr<Struct> up{};

(或std::shared_ptr).这样,指针被值初始化,nullptr即被分配给它.

有关默认构造函数的详细信息,请参见http://en.cppreference.com/w/cpp/memory/unique_ptr/unique_ptr.


如果您正在寻找一个默认初始化的"智能"指针nullptr,那么您可以编写一个包装器.一个非常以下基本版本:

#include <iostream>

template <typename T>
struct safe_ptr
{
    T* _ptr;
    explicit safe_ptr(T* ptr = nullptr):_ptr{ptr}{}
    operator T*() const {return _ptr;}
    safe_ptr& operator=(T* rhs)
    {
        _ptr = rhs;
        return *this;
    }
};

void test(int* p){}

int main()
{
    safe_ptr<int> s;
    if(s==nullptr)
        std::cout << "Yes, we are safe!" << std::endl;
    // test that it "decays"
    test(s);

    s = new int[10]; // can assign 
    delete[] s; // can delete
}
Run Code Online (Sandbox Code Playgroud)