繁体   English   中英

c ++模板和const(使用auto时违反编译器警告)

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

码:

#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";
}

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

(因为您没有const构造函数,所以我假设const声明是普通副本,然后将结果视为const-仍然希望得到警告)

这些是我使用auto(我通常使用auto complete)尝试的第一步,没有裸露的指针,我会使用标准库的指针,但这更多的是练习,如果有的话,我想习惯于使用traits和其他类型公用事业

预期:
自动工作,它正确地获得了(我将鼠标悬停在我的IDE中,并且事实证明工作正常,确认编译器正在执行我所期望的工作)在前两个条件下有效,也就是说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资格。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM