gpt4 book ai didi

c++ - const XX 丢弃限定符 [- fpermissive]

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:24:04 24 4
gpt4 key购买 nike

在下面的代码片段 1 中,mKnownSRList 定义如下:

std::vector<EndPointAddr*> mKnownSRList;

我收到代码片段 2 中显示的编译错误。你能告诉我这段代码有什么问题吗? getTipcAddress() 和 compareTo 函数的内容显示在下面的代码片段 3 和 4 中。

CODE SNIPPET 1(标出编译错误)

void 
ServiceRegistrarAPI::removeKnownSR(EndPointAddr & srEndPointAddr)
{
auto last =
std::remove_if(mKnownSRList.begin(),
mKnownSRList.end(),
[srEndPointAddr]( EndPointAddr* o )
{
//LINE 355 is the following
EndPointTipcAddr myTipcAddress = srEndPointAddr.getTipcAddress();
EndPointTipcAddr otherTipcAddress = o->getTipcAddress();

return (myTipcAddress.compareTo(otherTipcAddress));
});

if(*last != nullptr)
{
delete *last;
}

mKnownSRList.erase(last, mKnownSRList.end());
}

SNIPPET 2(编译错误)

  ServiceRegistrarAPI.cpp:355:72: error: passing ‘const EndPointAddr’ as ‘this’   argument of ‘EndPointTipcAddr& EndPointAddr::getTipcAddress()’ discards qualifiers [-  fpermissive]

代码片段 3(getTipcAddress 函数)

EndPointTipcAddr & getTipcAddress() { return mTipcAddress; }

CODE NIPPET 4(compareTo 函数)

  bool

EndPointTipcAddr::compareTo(EndPointTipcAddr &rhs)
{
if( (mType == rhs.getType()) && (mInstanceNo == rhs.getInstanceNo()) )
{
return true;
}

return false;
}

最佳答案

参见 S5.1.2.5:

The closure type for a lambda-expression has a public inline function call operator (13.5.4) whose parameters and return type are described by the lambda-expression’s parameter-declaration-clause and trailingreturn- type respectively. This function call operator is declared const (9.3.1) if and only if the lambdaexpression’s parameter-declaration-clause is not followed by mutable. It is neither virtual nor declared volatile. Default arguments (8.3.6) shall not be specified in the parameter-declaration-clause of a lambdadeclarator. Any exception-specification specified on a lambda-expression applies to the corresponding function call operator. An attribute-specifier-seq in a lambda-declarator appertains to the type of the corresponding function call operator. [ Note: Names referenced in the lambda-declarator are looked up in the context in which the lambda-expression appears. —end note ]

基本上,这意味着生成的仿函数的 operator() 默认是 const,并且您已经按值捕获,并且这个捕获的变量是生成的仿函数的成员。

所以,您有两个选择:

  1. 通过引用而非值进行捕获。
  2. 将您的 lambda 更改为以下内容(注意参数声明子句后面的 mutable):

    [srEndPointAddr](EndPointAddr* o) 可变 { ... }

关于c++ - const XX 丢弃限定符 [- fpermissive],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15618415/

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