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";
}
没有生成警告,有一个ref计数指针的构造函数,它采用const ref计数ptr(复制构造函数(-ref计数是可变的。尽管如此,我还是希望得到警告。
(由于你不能有const构造函数,我假设const声明是一个正常的副本,然后将结果视为const-我仍然希望得到警告(
这是我冒险使用auto(我通常使用auto-complete(和无裸指针的第一步,我会使用标准库的指针,但如果有什么不同的话,这更像是一种练习,我想习惯使用traits和其他类型的实用程序
预期:
自动工作,它正确地获得了前两个,也就是说reference
和other
工作正常。
它没有(我的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
资格。
相关文章:
- 如何修复编译器警告 C6386 和 C6385?
- 编译器警告:执行到达值返回函数的末尾而不返回值
- 为什么布尔开关语句有编译器警告?
- 奇怪的缩小转换在 g++ 编译器中加倍到浮点警告
- 处理编译器关于可能丢失数据的警告的最优雅方法是什么
- 使用 reverse_iterator 而不是const_reverse_iterator并获得讨厌的编译器警告和错误
- 添加 c++11 编译器后打开 devc++ 时显示的警告
- 来自 std::chrono 的编译器警告,但未被使用
- 警告级别为 3 的 int 的 std::vector push_back 处的编译器警告
- G++ 编译器未为未定义的方法生成错误/警告
- 从 int 中剥离位时,编译器会警告一个转换,但不警告其他转换.有解决方法吗?
- 有没有办法在从临时返回按值string_view时获得编译器警告?
- 常量更改而不const_cast<> 为什么没有编译器警告/错误?
- 为什么编译器不在同一翻译单元中警告 ODR 违规
- C++语法错误,编译器不会警告或 int v = func(&v) 出错;
- C++ 添加编译器警告,以错误使用自定义打印/日志功能
- 我正在尝试在我的类中创建一个静态成员,但编译器警告我它是未定义的
- 是否可以将移动的变量标记为不再可用,并在使用它时收到编译器警告?
- 为什么我应该始终启用编译器警告
- 使用Boost :: black在boost :: variant中使用时,请警告编译器