c++ - 无法取消引用指针
问题描述
我正在用 C++11 编写 Haskell Maybe Monad 的实现。
但是,当我尝试测试代码时,我被卡住了。当我用伪构造函数构造一个类型的值,Just
然后尝试使用函数fromJust
(应该只是“解包”放置在 Maybe 中的值)来评估它时,程序停止并最终静默终止。
所以我试图调试它;这是 testMaybe.cpp 代码的输出:
c1
yeih2
value not null: 0xf16e70
我添加了几个打印语句来评估程序停止的位置,它似乎停止在我取消引用指针以返回值的确切位置。(我已经在代码中标记了。)
起初我认为可能在我想取消引用指针时可能已经解构了,据我了解,这将导致未定义的行为或终止。但是,我找不到会发生这种情况的地方。
你能告诉我为什么会这样吗?
testMaybe.cpp:
#include<iostream>
#include "Maybe.hpp"
using namespace std;
using namespace Functional_Maybe;
int main() {
Maybe<string> a{Maybe<string>::Just("hello") };
if(!isNothing(a)) cout << "yeih2 " << fromJust(a) << endl;
return 0;
}
也许.hpp
#pragma once
#include<stdexcept>
#include<iostream>
using namespace std;
namespace Functional_Maybe {
template <typename T>
class Maybe {
const T* value;
public:
Maybe(T *v) : value { v } {} //public for return in join
const static Maybe<T> nothing;
static Maybe<T> Just (const T &v) { cout << "c1" << endl; return Maybe<T> { new T(v) }; }
T fromJust() const {
if (isNothing()) throw std::runtime_error("Tried to extract value from Nothing");
cout << "\nvalue not null: " << value << " " << *value << endl;
// ^ stops here
return *value;
}
bool isNothing() const { return value==nullptr; }
~Maybe() { if (value != nullptr) delete value; }
};
template <typename T>
bool isNothing(Maybe<T> val) {
return val.isNothing();
}
template <typename T>
T fromJust(Maybe<T> val) {
return val.fromJust();
}
}
解决方案
你的类模板Maybe
拥有资源(动态分配的T
),但不遵循三原则:(隐式定义的)复制和移动操作只做浅拷贝,这导致了use-after-free和double-free问题。您应该为您的类实现正确的复制和移动操作(构造函数和赋值运算符),或者std::unique_ptr<const T>
用作 的类型value
,并删除您的手动析构函数(从而遵循首选的零规则)。
旁注:您是否研究过std::optional
(或者,在 C++17 之前的版本中,boost::optional
)?他们似乎正在做一些与您提议的课程非常相似(甚至相同)的事情,您可能想要使用它们(或者如果更适合您,则在您的课程内部使用它们)。它们甚至可能更有效,在某些情况下使用小对象优化来避免动态内存分配。
推荐阅读
- python - 在 Python 中将字典值转换为数组
- android - 使用 Flutter 的 Firebase
- typescript - 如何实现接口?
- python - 如何让我的解析数据落入某些列?[Python]
- azure - 如何获得 MFA 类型的 id?(Azure B2C 自定义策略 MFA)
- next.js - NextJS _error.js 不为 API 路由呈现?还有什么方法可以一致地处理和记录 API 错误?
- python - python lambda中的keyerror-alexa技能
- python - CRITICAL] [Clock ] 警告,在下一帧之前完成了太多迭代
- python - 从 HTML 中获取 json
- flutter - 没有为“Stack”类定义 getter ClipBehavior