gpt4 book ai didi

c++ - STL std::map,通过ref传递给const以及const_casting的必要性

转载 作者:太空狗 更新时间:2023-10-29 20:31:25 24 4
gpt4 key购买 nike

我有一个关于 const_cast 的简单问题和关于 STL 容器的最佳实践。考虑以下类 Foo 有一个从 Widget*int 的私有(private) STL std::map:

声明:

#include <map>  
using std::map;

class Widget;

class Foo {
public:
Foo(int n);
virtual ~Foo();

bool hasWidget(const Widget&);

private:
map<Widget*,int> widget_map;
};

定义:

#include <map>
#include "Foo.h"
#include "Widget.h"

using std::map;

Foo::Foo(int n)
{
for (int i = 0; i < n; i++) {
widget_map[new Widget()] = 1;
}
}

Foo::~Foo()
{
map<Widget*, int>::iterator it;
for (it = widget_map.begin(); it != widget_map.end(); it++) {
delete it->first;
}
}

bool Foo::hasWidget(const Widget& w)
{
map<Widget*, int>::iterator it;
it = this->widget_map.find(const_cast<Widget*>(&w));
return ( ! ( it == widget_map.end() ) );
}

鉴于 hasWidget 将对 const 的引用作为其参数,因此在调用 map::find 时需要丢弃常量(wiget_mapWiget*int)。据我所知,这种方法既明智又可取——但如果没有更有经验的 C++ 程序员的反馈,我不愿意接受它。

在我看来,这是适当使用 const_cast 的少数情况之一,因为我们将转换的结果传递给 STL 方法。我说得对吗?

我意识到已经提出了这个问题的其他排列(例如,const_cast for vector with object),但似乎没有一个直接解决上述问题。

提前致谢。

最佳答案

我想我的回答会陷入“主观和争论”,但我会试一试......

const_cast 我并不害怕,但我对您的设计持怀疑态度。成员函数 hasWidget 通过 const ref 获取其参数:这对客户端说什么?从客户端的角度来看,如果我不知道实现,我可能会认为每个 Widget按值与范围。对我来说,界面不反射(reflect)实际行为,它比较Widget 按地址

例如,当前签名允许传递一个临时的Widget,尽管在​​这种情况下返回值永远不会是true。我会亲自将签名更改为(注意我添加了一个const):

bool hasWidget(const Widget *) const;

关于c++ - STL std::map,通过ref传递给const以及const_casting的必要性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4312789/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com