gpt4 book ai didi

c++ - C++有自初始化指针吗

转载 作者:太空狗 更新时间:2023-10-29 23:50:35 26 4
gpt4 key购买 nike

问这么简单的问题我有点不好意思:

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

写:

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

std::ptr<Struct> p;
// ...
p = new Struct;
// ...
someFunction(p);

有这样的事吗?或者可能在 boost 或 Qt 中?

编辑:明确地说:我不是在搜索一个智能指针,它拥有指针的所有权并进行引用计数。

最佳答案

你可以使用下面的语法

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
}

关于c++ - C++有自初始化指针吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28859404/

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