2014-06-17 23 views
0

代码:C++模板和const(违反不使用自动编译器警告)

#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计数PTR(拷贝构造) - 裁判计数是可变的。我仍然期待警告。

(正如你不能有常量构造我会假设常量声明是一个正常的拷贝,然后处理结果为const - 还是我期望的警告)

这是我的第一个步骤冒险使用自动(我通常使用自动完成),没有裸指针,我会使用标准库的,但这是更多的练习,如果有的话,我想习惯使用特征和其他类型的实用程序

预计:
自动工作,它正确得到(我鼠标在我的IDE和事实的东西作品确认编译器正在做我期望的)前两个,也就是说referenceother工作正常。

它没有(也没有我的IDE)得到test正确的,那就是它丢弃const和(正如你所看到的),我可以使用“setThing”,我不应该这样做。

附录

复制构造:

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

你的问题是什么?您没有SSCCE示例。 –

+0

这听起来像你的IDE是错的,你的编译器是正确的。 – juanchopanza

+0

@juanchopanza既没有为'auto test = other;'行产生警告,但都认识到'other'是const,但'test'不是。 –

回答

2

当你说

auto test = other; 

您创建的otherconst副本。显然,从const对象创建副本没有问题,也不存在对非const对象调用的函数的限制。如果你想创建的参考,你已经写

auto&& test = other; 

这将保持const资格,效果显着。

+0

'\t RefCountedPtr(const RefCountedPtr&from){ \t \t refCount = from.refCount; \t \t(* refCount)++; \t \t data = from.data;我可以期待这个警告(我放弃了数据的常量),我可以创建一个“const构造函数”或一种方法来转换为一个“const Object”作为模板参数ref计数指针? –

+0

复制分配也可以将'const'对象赋给非''const'对象。 ...因为你的对象似乎是一个指针,而不是包含对象的'const'限定影响指针的const属性,而不是指针。 –

+0

为什么'自动&&'?不是'自动&'够了吗? –