指向以其他方式分配的东西在C++中是否合理安全?
到目前为止,我一直在使用STL容器(在一种情况下,一个数组,但这是另一个问题)满足我所有的动态内存需求,因此我不需要显式使用该new关键字.我也很乐意使用普通的ol' int *foo类型指针来引用事物.现在我正在阅读关于智能指针的内容(我在Java上磨口,所以我以前从未担心过这个问题)而传统的智慧似乎是"裸指针不好,不要使用它们".
那我有多麻烦?我可以安全地继续使用裸指针,只要它们指向的东西有其他破坏条件吗?这是我可以逃避的事情,但将来应该避免吗?或者这是一场灾难,我应该在匆忙之后修复?
这是非常基本的.
我记得在某个地方发现了一个警告(我现在找不到),你不应该直接修改STL容器的内容,因为它可能会破坏容器的内部记录.从那以后,只要你想要修改一个元素,就应该使用boost的ptr_containers之类的东西.
这基本上就是我想要做的:
int main (int argc, char *argv[]) {
std::vector<int> jambone;
jambone.push_back(2);
jambone.front() = 4;
std::cout<< jambone.front();
}
Run Code Online (Sandbox Code Playgroud)
我不想在这里用多线程或任何东西做任何事情.那应该没事,对吧?如果它是一个装满物体的容器会不会有任何不同,我在其中一个上面调用了一个mutator?
我创建了一个类并将其分成源文件和头文件,但我无法让它们相互交谈。
我的头文件,GridLayout.h看起来像这样:
#ifndef GRIDLAYOUT_H_INCLUDED
#define GRIDLAYOUT_H_INCLUDED
#include <vector>
#include <types.h>
#include "GridPlaceable.h"
namespace Spaceships {
class GridLayout {
//consider replace with std::list
typedef std::vector<GridPlaceable*> column;
public:
GridLayout();
~GridLayout();
void arrange();
void splitColumn(size_t colNo, distance position);
void splitRow(size_t rowNo, distance position);
bool placeOne(GridPlaceable* thatOne);
private:
bool tryToFit(GridPlaceable* thatOne, size_t startCol, size_t startCell);
std::vector<column> wholeGrid;
std::vector<GridPlaceable*> toPlace;
std::vector<distance> rowHeights, colWidths;
std::vector<size_t> firstEmpties;
bool mandates;
};
};
Run Code Online (Sandbox Code Playgroud)
GridLayout.cpp好像:
#include "GridLayout.h"
namespace Spaceships {
GridLayout::GridLayout() {
}
//GridLayout::aBunchOfOtherFunctions() { }
} …Run Code Online (Sandbox Code Playgroud)