简体   繁体   中英

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. 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)

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

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.

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.

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 . 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. If you wanted to create reference, you'd have written

auto&& test = other;

which would keep the const qualification, obviously.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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