我和一位同事正在争论在全球范围内撰写此文章的可编辑性:
int* g_pMyInt = new int;
Run Code Online (Sandbox Code Playgroud)
我的论点围绕这样一个事实,即new在全局范围内调用函数是不可能的.令我惊讶的是,上面的编译得很好(MS-VC8和Apple的LLVM 3).
所以我继续尝试:
int* foo()
{
return new int;
}
int* g_pMyInt = foo(); // Still global scope.
Run Code Online (Sandbox Code Playgroud)
并且,编译也就像一个魅力(后来用类构造函数/析构函数测试打印出一条消息.ctor的消息经过,dtor没有.那时候不那么惊讶了.)
虽然这对我来说是非常错误的(没有有序/正确的方式/时间来调用删除),但编译器并未禁止它.为什么?
为什么不允许这样做?您正在做的就是初始化一个全局变量,非常欢迎您这样做,即使初始化涉及函数调用:
int i = 5 + 6;
double j(std::sin(1.25));
const Foo k = get_my_foo_on(i, 11, true);
std::ostream & os(std::cout << "hello world\n");
int * p(new int); // fine but very last-century
std::unique_ptr<int> q(new int); // ah, welcome to the real world
int main() { /* ... */ }
Run Code Online (Sandbox Code Playgroud)
当然,你需要担心删除动态分配的对象,无论它们是否在全局范围内分配......拥有资源的包装类,如unique_ptr理想的解决方案.
| 归档时间: |
|
| 查看次数: |
1155 次 |
| 最近记录: |