【发布时间】:2015-10-25 20:05:16
【问题描述】:
我经常使用已删除的函数错误。我只是将weighted_pointer 的指针更改为unique_ptr。但我不明白为什么会出现错误,有什么提示吗?
likeatree 是一个 DAG 结构,它可以根据掩码值指向另一个结构或 stdDeque 的元素。
weighted_pointer 的 weight 具有 mutable 关键字,因为不会改变集合中的位置。
#include <deque>
#include <set>
#include <vector>
#include <iostream>
#include <algorithm>
#include <memory>
#include <chrono>
using namespace std;
struct likeatree{
unsigned int mask : 3;
void * a;
void * b;
};
struct weighted_pointer{
mutable int weight;
unique_ptr<likeatree> ptr;
};
struct ptrcomp{
bool operator()(const weighted_pointer & lhs, const weighted_pointer & rhs) {
if(lhs.ptr->mask < rhs.ptr->mask)
return true;
if(lhs.ptr->mask > rhs.ptr->mask)
return false;
if(lhs.ptr -> a < rhs.ptr->a)
return true;
if(lhs.ptr->a > rhs.ptr->a)
return false;
return lhs.ptr->b < rhs.ptr->b;
}
};
vector<likeatree *> treeVector;
deque<bool> stdDeque(3);
vector<vector<bool>> boolMatrix{{0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0}};
set<weighted_pointer,ptrcomp> stdSet;
int main(){
srand(time(NULL));
likeatree * first_pointer = new likeatree{0,&input[0],nullptr};
likeatree * second_pointer = first_pointer;
unique_ptr<likeatree> tmp(first_pointer);
weighted_pointer wp;
wp.weight = 1;
wp.pointer = move(tmp);
stdSet.insert(move(wp));
// I'd like to do it inline(or more but with variables that end of scope here), but this don't work. (And i don't keep a copy of the pointer)
// stdSet.insert(move(weighted_pointer{1,move(make_unique<likeatree>(*new likeatree{0,&input[0],nullptr}))}));
return 0;
}
编辑:用一个单一的问题案例更改了代码 编辑:已解决。使用 make_unique 时缺少取消引用。
【问题讨论】:
-
如果您包含实际的编译器错误,您将获得更好的答案(并且可能对错误的解释有所了解)。您正在使用的编译器选项也很有用。我用
g++ -std=c++11 -c /tmp/31791982.cpp编译它没有错误(尽管我无法成功链接,因为缺少main())。 -
@TobySpeight -std=c++11 -Wall。主要在最后。
-
顺便说一句,你可以写
bool ptrcomp::operator()(const weighted_pointer& lhs, const weighted_pointer& rhs) { return std::tie(lhs.ptr->mask, lhs.ptr->a, lhs.ptr->b) < std::tie(rhs.ptr->mask, rhs.ptr->a, rhs.ptr->b); }。 -
@TobySpeight: 没有看到位域:-(,我们仍然可以在这里使用
make_tuple而不是std::tie。
标签: c++ c++11 smart-pointers