c++ - 带有指针和唯一指针的 emplace_back

标签 c++ pointers dictionary unique unique-ptr

关于 someFunctionOnesomeFunctionTwo

当每个都放置到 map 中时,最终结果是否仍然相同?

指针是否升级为智能指针?

struct MyStruct {
        int x = 0;
    };

std::unordered_map<int, std::unique_ptr<MyStruct>> m_map;

void someFunctionOne(int id, std::unique_ptr<MyStruct>& myStruct){
    m_map.emplace(id, std::move(myStruct));
}

void someFunctionTwo(int id, MyStruct * myStruct){
    m_map.emplace(id, myStruct);
}

int main()
{
    someFunctionOne(452, std::make_unique<MyStruct>());
    someFunctionTwo(10, new MyStruct);

    m_map.clear();
    return 0;
}

最佳答案

Does the pointer get upgraded to a smart pointer ?

正确的术语是 Implicit type conversion .但是,是的,这就是这一行中会发生的事情:

m_map.emplace(id, myStruct);

这是因为 unique_pointer 有一个具有签名的单值构造函数:

explicit unique_ptr( pointer p ) noexcept;

这就是将指针转换为 unique_ptr 的调用。

关于c++ - 带有指针和唯一指针的 emplace_back,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44747172/

相关文章:

c++ - error C3861 : '_T' : identifier not found , 无法将main函数参数作为函数参数传入

c++ - 如何检查和处理前提条件违规?

c++ - 使用指向基础抽象类的指针访问子类成员,这不能是 dynamic_cast

c - 为什么必须在以下代码中将结果变量声明为指针?

javascript - 处理 Meteor 和 mongodb 中的嵌套字典

c++ - 使用 CMake 更改底层 VERSION 文本文件时,如何始终重新生成版本头文件?

c++ - 关于 'using namespace std' 的问题?

c++ - union 体中指针和数组的不同地址

ios - 如何使用 Alamofire 发送 SwftyJSON?

Python:检查是否有任何列表元素是字典中的键