【发布时间】:2015-12-04 12:49:03
【问题描述】:
我有一个静态库,其中包含一些基本的 boost 图功能,全部封装在“vgraph”类中。
当使用共享指针实例化类时,它不起作用,一切似乎都未分配。 如果我不使用指针,它似乎没问题。
我错过了什么?当静态库中使用的代码集成到主源中时,智能指针一切正常。完全没有问题。
示例代码:
#ifndef testClass_hpp
#define testClass_hpp
#include <stdio.h>
#include <vector>
#include <string>
#include <random>
#include <iostream>
#include <memory>
class vGraph { // from the static library
public:
vGraph();
~vGraph();
void test();
unsigned long addVertex(bool _di);
void addEdge(unsigned long a, unsigned long b, bool _di = true);
int getNumVerts(bool di);
int getNumEdges(bool di);
std::vector<std::string> computeXD(bool choice);
std::vector<std::string> computeXDdi(bool choice);
int unlinkEdge(int a, int b);
int linkDiEdge(int a ,int b);
};
class testClass {
public:
void randomGraph();
std::shared_ptr<vGraph> graph;
};
#endif /* testClass_hpp */
#include "testClass.hpp"
void testClass::randomGraph() {
graph = std::make_shared<vGraph>();
std::vector<unsigned long> verts;
for (int i=0; i<2000; ++i) {
verts.push_back(graph->addVertex(true));
}
std::cout << graph->getNumVerts(true);
for (int i=0; i<5000; ++i) {
graph->addEdge(std::rand()%2000, std::rand()%2000);
}
graph->computeXDdi(true);
}
#
void main(){
testClass test;
test.randomGraph();
}
#
如果我用一个简单的 vGraph 图替换 std::shared_ptr 图,一切似乎都正常。 愚蠢的缺乏知识?
编辑以使事情更清楚。
编译工作没有错误。在运行时,如果我将 testClass 中的 vGraph 声明为 std::shared_ptr,则会出现未分配的内存错误。
喜欢:
malloc: *** error for object 0x648000021ce0: Invalid pointer dequeued from free list
*** set a breakpoint in malloc_error_break to debug
如果我使用共享指针,好像 vGraph 对象内部的东西没有正确初始化。
【问题讨论】:
-
你不是说
testClass test;在你的main函数中吗? -
正确! testClass 测试。
-
“当使用共享指针实例化类时它不起作用”,什么不起作用?您是否遇到任何编译错误或其他问题?
-
陈述您的问题 - 描述当前输出(行为、编译错误、段错误发生等)并描述您的预期输出(例如预期行为)
-
编译得很好,但是如果我尝试向图中添加一个顶点,我会遇到未分配的内存问题。就像没有发生适当的初始化一样。见编辑。
标签: c++ boost clang static-libraries