我将发布我的代码然后解释我的查询:
typedef std::shared_ptr<SEntity> Entity;
//Scene_Ids is an enum
static std::map<Scene_Ids, std::vector<Entity> > m_scene_entities;
std::shared_ptr<SEntity>& SEntityManager::getEntity(const std::string& entity_name)
{
int counter = 0;
for (auto iter = m_scene_entities.begin(); iter != m_scene_entities.end(); ++iter)
{
if (iter->second[counter]->getId() == entity_name)
return iter->second[counter];
counter++;
}
//What would I return if the entity couldn't be found?
}
Run Code Online (Sandbox Code Playgroud)
代码基本上解释了这一切.我有一个方法,如果在地图内的std :: vector中找到"实体",它将返回对它的std :: shared_ptr类型的引用.但是,由于我没有返回指针,我无法返回nullptr.在失败的情况下我能回报什么?
另外,我知道std :: shared_ptr意味着在几个不同的地方有副本.为此,我真的需要返回一个引用,还是可以按值返回它?
谢谢!
我有一个函数,它接受类型的共享指针Base,然后std::dynamic_pointer_cast指向派生类型。但是,派生指针是 NULL,我不明白为什么。我已确保在我的基类中包含一个虚拟析构函数。我不想使用静态强制转换,因为这不能保证我的派生成员变量和函数被保留?
代码如下:
基类:
class Base
{
public:
mType get_type()
{
return msg_type;
}
void set_type(mType type)
{
msg_type = type;
}
virtual ~cMsg() = default;
protected:
mType msg_type;
message msg;
};
Run Code Online (Sandbox Code Playgroud)
派生类:
class Derived : public Base
{
public:
void set_i(int j)
{
i = j;
}
int get_i()
{
return i;
}
private:
int i;
};
Run Code Online (Sandbox Code Playgroud)
功能执行演员表:
void callback(std::shared_ptr<Base> msg_received)
{
std::cout<< "Callback called\n";
auto real_msg = std::dynamic_pointer_cast<Derived>(msg_received);
if (real_msg != NULL)
{
std::cout …Run Code Online (Sandbox Code Playgroud) 我有一个shared_ptr<SomeClass>名为的矢量allParts.
代码如下:
void function thisIsWhereItStarts(){
vector<shared_ptr<SomeClass> > allParts;
for(i=0;i<N;i++){
allParts.push_back(function_which_returns_shared_ptr_someclass());
}
// Then I use this vector as below:
for(vector<shared_ptr<SomeClass> >::iterator it = allParts.begin(); it!=allParts.end(); it++){
(*it)->function_of_SomeClass() ; // THIS GIVES SEGMENTATION FAULT
}
}
Run Code Online (Sandbox Code Playgroud)
我以前曾多次使用指针向量,但这是我第一次使用shared_ptr.
返回的函数shared_ptr是这样的:
shared_ptr<SomeClass> function_which_returns_shared_ptr_someclass(){
shared_ptr<SomeClass> part(new SomeClass);
if(part->some_function(some_parameter)){
return part;
}else{
return shared_ptr<SomeClass>();
}
}
Run Code Online (Sandbox Code Playgroud) 我决定并行化我写的一个巨大的程序,最后我遇到了新的C++ 11智能指针.
我有一个例程,应该执行多次(通常超过1000次),这有点贵.它是在一个简单的for循环中运行的,我所做的是在一个方法中安装这个for循环,该方法将由一些工作线程运行.
是这样做的,做了一些参数包裹std::shared_ptr,关注竞争条件,一切似乎都很好.
但现在,有些时候,进程将被中止,我会收到以下错误之一:
进程以退出代码139结束(由信号11中断:SIGSEGV)
要么
malloc.c:2395:sysmalloc:断言`(old_top == initial_top(av)&& old_size == 0)|| ((unsigned long)(old_size)> = MINSIZE && prev_inuse(old_top)&&((unsigned long)old_end&(pagesize - 1))== 0)'失败.
并行for正在进行时发生所有这些错误; 不是之前,不是一开始,不是最后,而是介于两者之间,这让我闻起来像一个未被覆盖的竞争条件.
该程序是巨大的,但我创建了一个能够重现问题的缩影:
#include <iostream>
#include <vector>
#include <unordered_map>
#include <thread>
#include <set>
#include <memory>
#include <atomic>
namespace std {
template <>
struct hash<std::multiset<unsigned long>>
{
std::size_t operator()(const std::multiset<unsigned long>& k) const
{
std::size_t r = 0;
bool shift = false;
for (auto&& it : k) {
r = (r >> !shift) ^ (std::hash<unsigned long>()(it) …Run Code Online (Sandbox Code Playgroud) 执行以下程序时应该怎么办?
#include <iostream>
#include <memory>
class test;
std::shared_ptr<test> a_test_object;
struct test
{
~test()
{
std::cout << "destroy test" << std::endl;
auto ptr = a_test_object;
}
};
int main()
{
a_test_object = std::make_shared<test>();
//a_test_object.reset(); // Uncomment this and it works fine.
}
Run Code Online (Sandbox Code Playgroud)
我在GCC和Visual Studio 2015上测试了这个,在这两种情况下程序都崩溃了.发生的事情是共享指针在其析构函数中递减计数,然后执行~test(),复制共享指针递增然后递减计数,触发对~test()的无限递归调用.奇怪的是,调用reset()不会触发问题.
我今天碰到了这个,因为使用了一个没有这个双重删除错误的前C++ 11版本的shared_ptr的旧代码被更新为使用std :: shared_ptr.令我惊讶的是,std :: shared_ptr导致程序崩溃.这真的是std :: shared_ptr的预期行为吗?
据我所知,取消引用 -*smart_ptr和get()+ 取消引用*smart_ptr.get()使用智能指针做同样的事情,但可能有一些我不知道的事情,因为我在第二种方法中看到了很多情况被使用了,那有什么意义呢?它会以任何方式影响性能吗?
我是 C++ 的新手,正在尝试对 shared_ptr (WIP) 进行非常基本的实现。我试图在通过取消引用找到基础值后立即在析构函数中删除堆分配的指针。虽然取消引用发生得很好,但删除 '''ref_count''' 变量会导致问题。有人可以帮忙吗?'''
#include<iostream>
template<typename T>
class shared_ptr{
private:
T* native_ptr_ = nullptr;
int* ref_count_ = nullptr;
inline void increment_count() {
*ref_count_++;
}
inline void decrement_count() {
*ref_count_--;
}
public:
shared_ptr() {
std::cout << "shared_ptr: empty constructor" << std::endl;
native_ptr_ = nullptr;
ref_count_ = nullptr;
}
shared_ptr(T* ptr) {
std::cout << "shared_ptr: constructor" << std::endl;
if (ptr) {
native_ptr_ = ptr;
ref_count_ = new int(1);
}
}
~shared_ptr() {
std::cout << "shared_ptr: destructor" << std::endl; …Run Code Online (Sandbox Code Playgroud) c++ destructor reference-counting shared-ptr delete-operator
我从函数中得到了 shared_ptr。共享 ptr 指向一个大的字节数组。我想返回这个 shared_ptr 但将它指向这个数组中的第 16 个字节。带有原始指针的示例(工作):
uint8_t* SomeFunction() {
uint8_t* array = SomeOtherFunction();
return array + 16;
}
Run Code Online (Sandbox Code Playgroud)
使用共享指针的示例(不起作用):
std::shared_ptr<uint8_t[]> SomeFunction() {
std::shared_ptr<uint8_t[]> array = SomeOtherFunction();
return array + 16;
}
Run Code Online (Sandbox Code Playgroud)
我不想重新分配数组,因为它很大而且重新分配需要时间。我想返回相同的共享 ptr,但它的get()方法将返回raw pointer+16。但在原始指针地址处释放内存。
我可以做吗?如何?
一个读取器线程和多个写入器线程同时访问shared_ptr对象并且它运行良好,代码如下(但是,如果我将写入行代码从“=”修改为“重置”,它将在读取时进行coredump):
shared_ptr.reset 意味着 coredump ,“operator =”意味着效果很好?(我试了100多次)
bool start = false;
std::mutex mtx;
std::condition_variable cond;
std::shared_ptr<std::string> string_ptr(new std::string("hello"));
int main() {
auto read = []() {
{
std::cout << "readddd" << std::endl;
std::unique_lock<std::mutex> lck(mtx);
while (!start) {
cond.wait(lck);
}
}
for (int i = 0; i < 100000; ++i) {
std::cout << *string_ptr.get() << std::endl;
}
};
auto write = []() {
{
std::unique_lock<std::mutex> lck(mtx);
while (!start) {
cond.wait(lck);
}
}
for (int i = 0; i < 100000; ++i) …Run Code Online (Sandbox Code Playgroud) 我试图在地图中存储一些派生类。
我使用 share_ptr 存储它们以避免意外的释放。
不幸的是,在我的尝试中,它是有效的:程序编译并执行,但我收到一条错误消息。
我获得了以下MWE:
#include <iostream>
#include <map>
#include <memory>
#include <string>
#include <typeindex>
#include <typeinfo>
using namespace std;
class DataInOut {
public:
std::shared_ptr<void> data = nullptr;
std::type_index type = typeid(nullptr);
bool initialized = false;
bool optional = false;
// template <class Archive>
virtual bool dummy_funct(int &ar, const char* charName){
cout<< "serialize_or_throw from DataInOut address is an empty function." << endl;
return true;
}
DataInOut *clone() const { return new DataInOut(*this); }
~DataInOut(){}; // Destructor
};
template <typename …Run Code Online (Sandbox Code Playgroud)