C++ 为什么MSVC14允许声明指向动态非初始化常量对象的指针?
在“C++初级教程第5版”第12章“动态内存和智能指针”中说: 与任何其他常量一样,必须初始化动态分配的常量对象。定义默认构造函数的类类型的常量动态对象(§7.1.4,第263页)可以隐式初始化。其他类型的对象必须显式初始化。因为分配的对象是const,所以new返回的指针是指向const的指针(§2.4.2,第62页) 这样的陈述被认为是错误的:C++ 为什么MSVC14允许声明指向动态非初始化常量对象的指针?,c++,dynamic-memory-allocation,C++,Dynamic Memory Allocation,在“C++初级教程第5版”第12章“动态内存和智能指针”中说: 与任何其他常量一样,必须初始化动态分配的常量对象。定义默认构造函数的类类型的常量动态对象(§7.1.4,第263页)可以隐式初始化。其他类型的对象必须显式初始化。因为分配的对象是const,所以new返回的指针是指向const的指针(§2.4.2,第62页) 这样的陈述被认为是错误的: const int* pi = new const int; 如果我在GCC上运行此语句,它将无法编译,但为什么它要在MSVC14上编译 在我看
const int* pi = new const int;
- 如果我在GCC上运行此语句,它将无法编译,但为什么它要在MSVC14上编译
- 在我看来,这是一个愚蠢的bug,指针是指向
的指针,这意味着以后无法分配给它,访问它也是一个错误const
- 这不是MSVC中的“bug”,因为这不是编译器的工作,而是运行时
const int ci; // error ci is a constant object in Stack-memory so it must be initialized at compile-time.
const int* cpi; // ok. just a pointer to const. The compiler doesn't know whether you'll assign an initialized const object or not.
int choice = 0;
std::cin >> choice;
if(choice == arbitraryValue)
cpi = new const int; // or cpi = new cont int(anotherArbitraryValue );
- 正如您所看到的,这是允许的,因为在编译时编译器不知道如何在运行时创建和初始化对象
- 看起来你在问:
int a[]{1, 2, 3, 4}; int index; cin >> index; // e.g: user enters 10 cout << a[i];
inta[]{1,2,3,4}; 整数指数; cin>>索引;//e、 g:用户输入10 cout这不是MSVC中的“bug”,因为这不是编译器的工作,而是运行时
const int ci; // error ci is a constant object in Stack-memory so it must be initialized at compile-time. const int* cpi; // ok. just a pointer to const. The compiler doesn't know whether you'll assign an initialized const object or not. int choice = 0; std::cin >> choice; if(choice == arbitraryValue) cpi = new const int; // or cpi = new cont int(anotherArbitraryValue );
- 正如您所看到的,这是允许的,因为在编译时编译器不知道如何在运行时创建和初始化对象
- 看起来你在问:
int a[]{1, 2, 3, 4}; int index; cin >> index; // e.g: user enters 10 cout << a[i];
inta[]{1,2,3,4}; 整数指数; cin>>索引;//e、 g:用户输入10
cout非标准编译器扩展。(bug/feature)MSVC不知道它是最一致的编译器。从程序员的角度来看,它很愚蠢吗?对从编译器的角度来看——没有那么多。只是另一种不合规的行为<代码>结构条{};新康斯特酒吧代码>编译得很好。@HansPassant:我认为在您的示例中,这是一种未定义的行为,因为使用
来丢弃原始常量对象的常量。@HansPassant:但是在指向常量对象的指针上使用const_cast
来更改这些对象是错误的。是不是??!!!非标准编译器扩展。(bug/feature)MSVC不知道它是最一致的编译器。从程序员的角度来看,它很愚蠢吗?对从编译器的角度来看——没有那么多。只是另一种不合规的行为<代码>结构条{};新康斯特酒吧代码>编译得很好。@HansPassant:我认为在您的示例中,这是一种未定义的行为,因为使用const_cast
来丢弃原始常量对象的常量。@HansPassant:但是在指向常量对象的指针上使用const_cast
来更改这些对象是错误的。是不是??!!!const_cast