我有类似于shared_ptr<Type> t(makeSomething(), mem_fun(&Type::deleteMe))
我现在需要调用需要指针的C样式函数Type.我怎样才能得到它shared_ptr?
我的问题shared_ptr与make_sharedC++ 11有关.我有两个向量,第一个存储智能指针,第二个存储原始指针.第一个向量就像我已经过了一样,但是vector2只是令人困惑......
#include <iostream>
#include <vector>
#include <memory>
int main() {
std::vector<std::shared_ptr<int>> vector1;
vector1.push_back(std::make_shared<int>(1));
vector1.push_back(std::make_shared<int>(2));
vector1.push_back(std::make_shared<int>(3));
std::vector<int*> vector2;
vector2.push_back(std::make_shared<int>(4).get());
vector2.push_back(std::make_shared<int>(5).get());
vector2.push_back(std::make_shared<int>(6).get());
std::cout << "vector1 values:" << std::endl;
for(auto &value: vector1) { std::cout << *value << std::endl; }
std::cout << "vector2 values:" << std::endl;
for(auto &value: vector2) { std::cout << *value << std::endl; }
return 0;
}
Run Code Online (Sandbox Code Playgroud)
vector1 values:
1
2
3
vector2 values:
6
6
6
Run Code Online (Sandbox Code Playgroud)
我意识到创建原始指针并且不尝试转换智能指针会更简单但是让我很好奇知道为什么会发生这种情况?另外为什么每次推送都会改变vector2中的所有值?
以下是我在stackoverflow中发现的一些问题,但他们没有回答我的问题,或者我不明白答案......