我正在经历Josuttis的"使用Map作为关联数组"(来自The C++ Standard Library - A Tutorial and Reference,2nd Edition),并且遇到了使用std :: map作为 Stack Overflow上的关联数组.现在我对插入地图时调用的构造函数有了更多的疑问.
这是我的示例程序(不使用最佳编码实践;请原谅我):
class C
{
public:
string s;
C() { cout << "default " << endl;}
C(const string& p) : s(p)
{ cout << "one param" << endl;}
C(const C& obj)
{
if (this != &obj)
{
s = obj.s;
}
cout << "copy constr" << endl;
}
C& operator = (const C& obj)
{
if (this != &obj)
{
s = …Run Code Online (Sandbox Code Playgroud) 感谢所有的回复.
我重新格式化了我的问题,以便在包含类的构造函数抛出异常之后理解成员指针的状态
我的示例类:)
class Foo
{
public:
Foo()
{
int error = 0;
p = new Fred;
throw error; // Force throw , trying to understand what will happen to p
}
~Foo()
{
if (p)
{
delete p;
p = 0;
}
}
private:
Fred* p;
};
int main()
{
try
{
Foo* lptr = new Foo;
}
catch (...)
{}
}
Run Code Online (Sandbox Code Playgroud)
类foo的consturctor会因某些随机原因而抛出异常.我知道foo的desturctor永远不会被调用,但在这种情况下,p的析构函数会被调用吗?
将p作为增强智能指针而不是指向fred的原始指针有什么不同.
谢谢.
我是c ++中hash_map的新手.我必须将表转换为hashmap.
这就是我在程序中声明和使用hash_map的方法
我正在使用微软视觉工作室.
#include <hash_map>
using namespace stdext;
typedef hash_multimap <const char*, long > HEAPTABLE;
typedef HEAPTABLE::iterator HEAP_ITER;
class CTest
{
public:
void setSwitchID(long i);
long getSwitchID();
void isUpgrading(bool bTest);
private:
HEAPTABLE m_hashMap;
};
void CTest::setSwitchID(long dwID)
{
HEAP_ITER hIter = m_hashMap.find("SwitchId");
if (hIter != m_hashMap.end())
{
hIter->second = dwID;
}
else
{
m_hashMap.insert(make_pair("SwitchId", dwID));
}
}
long CTest::getSwitchID()
{
HEAP_ITER hIter = m_hashMap.find("SwitchId");
if (hIter != m_hashMap.end())
{
return hIter->second;
}
return 0;
}
int _tmain(int argc, _TCHAR* …Run Code Online (Sandbox Code Playgroud)