c++模板和const(使用auto在没有编译器警告的情况下发生冲突)

c++ templates and const (violation without compiler warning using auto)

本文关键字:警告 编译器 情况下 冲突 const auto 使用 c++      更新时间:2023-10-16

代码:

#include "utils/LinkedList.h"
#include "utils/RefCount.h"
#include <iostream>
#include "utils/testobject.h"
int Object::nextId = 0;
int main(void) {
    ::Utils::LinkedList<::Utils::RefCountedPtr<Object>> list;
    list.append(new Object());
    auto reference = list[0];
    const auto other = list[0];
    //both IDE and GCC see below line as error:
    //with: error: passing ‘const Object’ as ‘this’ argument of ‘void Object::setThing(int)’ discards qualifiers [-fpermissive]
    //other->setThing(3);
    auto test = other;
    //this is fine - IT SHOULD NOT BE
    test->setThing(5);
    ::std::cout<<"Id: "<<other->getId()<<"n";
}

没有生成警告,有一个ref计数指针的构造函数,它采用const ref计数ptr(复制构造函数(-ref计数是可变的。尽管如此,我还是希望得到警告。

(由于你不能有const构造函数,我假设const声明是一个正常的副本,然后将结果视为const-我仍然希望得到警告(

这是我冒险使用auto(我通常使用auto-complete(和无裸指针的第一步,我会使用标准库的指针,但如果有什么不同的话,这更像是一种练习,我想习惯使用traits和其他类型的实用程序

预期:
自动工作,它正确地获得了前两个,也就是说referenceother工作正常。

它没有(我的IDE也没有(正确地处理test,也就是说它丢弃了const,并且(正如你所看到的(我可以使用"setThing",这是我不应该做的。

附录

复制构造函数:

RefCountedPtr(const RefCountedPtr& from) {
    refCount = from.refCount;
    (*refCount)++;
    data = from.data;
}

当你说时

auto test = other;

您创建了other的非const副本。显然,从const对象创建副本没有问题,也没有对在非const对象上调用函数的限制。如果你想创建参考,你会写

auto&& test = other;

这显然将保持const资格。