简体   繁体   English

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

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

Code: 码:

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

There are no warnings generated, there is a constructor for the ref counted pointer that takes a const ref counted ptr (copy constructor) - the ref count is mutable. 没有警告生成,有一个引用计数指针的构造函数,该指针采用const ref counted ptr(复制构造函数)-引用计数是可变的。 Still I'd expect a warning. 我还是希望得到一个警告。

(As you can't have const constructors I'd assumed that a const declaration was a normal copy followed by treating the result as const - still I'd expect a warning) (因为您没有const构造函数,所以我假设const声明是普通副本,然后将结果视为const-仍然希望得到警告)

These are my first steps venturing out using auto (I usually use auto complete) and no naked pointers, I would use the standard library ones but this is more of an exercise if anything, I want to get used to using traits and the other type utilities 这些是我使用auto(我通常使用auto complete)尝试的第一步,没有裸露的指针,我会使用标准库的指针,但这更多的是练习,如果有的话,我想习惯于使用traits和其他类型公用事业

Expected: 预期:
auto worked, it correctly gets (I mouse over in my IDE and the fact stuff works confirms the compiler is doing what I expect) on the first two, that's to say reference and other work fine. 自动工作,它正确地获得了(我将鼠标悬停在我的IDE中,并且事实证明工作正常,确认编译器正在执行我所期望的工作)在前两个条件下有效,也就是说referenceother工作正常。

It doesn't (and nor does my IDE) get test right, that is it discards the const and (as you can see) I can use "setThing" which I should not be able to do. 它没有(也没有我的IDE)得到正确的test ,即它丢弃了const并且(如您所见)我可以使用“ setThing”,这是我不应该做的。

Addendum 附录

Copy constructor: 复制构造函数:

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

When you say 当你说

auto test = other;

you create a non- const copy of other . 您创建other的非const副本。 Clearly, there is no issue creating a copy from a const object nor is there a restriction on functions being called on non- const objects. 显然,从const对象创建副本没有问题,在非const对象上调用函数也没有限制。 If you wanted to create reference, you'd have written 如果您想创建参考,则需要编写

auto&& test = other;

which would keep the const qualification, obviously. 显然,它将保留const资格。

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

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