我有这个C++代码:
#include <iostream>
using namespace std;
struct MyItem
{
  int value;
  MyItem* nextItem;
};
int main() {
    MyItem item = new MyItem;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)
我收到错误:
error: conversion from `MyItem*' to non-scalar type `MyItem' requested
Run Code Online (Sandbox Code Playgroud)
用g ++编译.那是什么意思?这是怎么回事?
在C#中,结构是值类型,但我能够将new它们视为引用类型.为什么是这样?
我正在玩内存动态分配,但我不明白.当用new语句分配一些内存时,我应该能够破坏指针指向使用的内存delete.
但是当我尝试时,这个delete命令似乎不起作用,因为指针指向的空间似乎没有被清空.
让我们以这个真正基本的代码为例:
#include <iostream>  
using namespace std;
int main()  
{  
    //I create a pointer-to-integer pTest, make it point to some new space,  
    // and fulfill this free space with a number;  
    int* pTest;  
    pTest = new int;  
    *(pTest) = 3;  
    cout << *(pTest) << endl; 
    // things are working well so far. Let's destroy this
    // dynamically allocated space!
    delete pTest;
    //OK, now I guess the data pTest pointed to has been destroyed …Run Code Online (Sandbox Code Playgroud) 假设我有以下代码段.
int main()
{
    int num;
    int* cost;
    while(cin >> num)
    {
        int sum = 0;
        if (num == 0)
          break;
        // Dynamically allocate the array and set to all zeros
        cost = new int [num];
        memset(cost, 0, num);
        for (int i = 0; i < num; i++)
        {
            cin >> cost[i];
            sum += cost[i];
        }
        cout << sum/num;
    }
`  `delete[] cost;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)
虽然我可以delete在while循环中为我的代码移动语句,但为了理解目的,我想知道代码在编写时会发生什么.每次使用运算符时C++都会分配不同的内存空间new吗?
运算符delete只删除最后分配的cost数组吗?
我正在研究jQuery的插件,我收到了这个JSLint错误:
Problem at line 80 character 45: Do not use 'new' for side effects.
(new jQuery.fasterTrim(this, options));
Run Code Online (Sandbox Code Playgroud)
我没有太多运气找到有关此JSLint错误或new可能有任何副作用的信息.
我试过谷歌搜索 "不要使用'新'副作用." 得到0结果.Binging给了我2个结果,但他们都只引用了JSLint源代码.希望这个问题会改变这一点.:-)
更新#1: 以下是上下文的更多来源:
  jQuery.fn.fasterTrim = function(options) {
    return this.each(function() {
      (new jQuery.fasterTrim(this, options));
    });
  };
Run Code Online (Sandbox Code Playgroud)
更新#2: 我使用Starter jQuery插件生成器作为我的插件的模板,其中包含该代码.
可能重复:
类型名称后的括号是否与new有所不同?
所以我在我的主要:
Class* pC = new Class;
Run Code Online (Sandbox Code Playgroud)
它的工作原理是
Class* pC = new Class();
Run Code Online (Sandbox Code Playgroud)
我今天才意识到我省略了括号(所以我在某种程度上被最令人烦恼的解析的"对立"所击中).
我的问题:这两种形式是否相同?
当我们重载类的new运算符时,我们将该函数声明为成员函数.例如:
class OpNew {
public:
    OpNew() { cout << "OpNew::OpNew()" << endl;}
    void* operator new(size_t sz) {
         cout << "OpNew::new: "
            << sz << " bytes" << endl;
         return ::new char[sz];
    }
};
Run Code Online (Sandbox Code Playgroud)
声明如何在幕后OpNew *obj = new OpNew工作?因为重载new是OpNew类的成员而不是静态的.那么编译器如何确保对new成员函数的调用成功呢?
根据C++参考,您可以通过以下方式新建一个对象:
MyClass * p1 = new MyClass;
Run Code Online (Sandbox Code Playgroud)
或者
MyClass * p2 = new (std::nothrow) MyClass;
Run Code Online (Sandbox Code Playgroud)
第二个将返回空指针而不是抛出异常.
但是,根据我的经验,我几乎看不到这个版本.
例如,谷歌不建议在他们的代码中使用异常,但我们可以看到他们没有在Chromium中使用nothrow版本.
是否有任何理由我们更喜欢默认的一个而不是一个?即使在没有使用异常的项目中?
- 编辑 -
跟进问题:我应该检查返回值malloc()吗?
看起来,相反,许多人建议检查malloc的返回值,有些人说是因为:
许多分配失败与内存不足无关.碎片可能导致分配失败,因为即使有足够的可用内存,也没有足够的连续空间可用.
这是真的?为什么我们在这种情况下对待malloc()和new()不同?
使用时分配数组时new [],为什么不能从指针中找出该数组的大小?它必须在运行时delete []知道,否则不知道要释放多少内存.
除非我错过了什么?
就我对资源管理的了解而言,在堆上分配一些东西(操作符new)应该总是比在堆栈上分配(自动存储)慢,因为堆栈是基于LIFO的结构,因此它需要最少的簿记,并且要分配的下一个地址的指针是微不足道的.
到现在为止还挺好.现在看下面的代码:
/* ...includes... */
using std::cout;
using std::cin;
using std::endl;
int bar() { return 42; }
int main()
{
    auto s1 = std::chrono::steady_clock::now();
    std::packaged_task<int()> pt1(bar);
    auto e1 = std::chrono::steady_clock::now();
    auto s2 = std::chrono::steady_clock::now();
    auto sh_ptr1 = std::make_shared<std::packaged_task<int()> >(bar);
    auto e2 = std::chrono::steady_clock::now();
    auto first = std::chrono::duration_cast<std::chrono::nanoseconds>(e1-s1);
    auto second = std::chrono::duration_cast<std::chrono::nanoseconds>(e2-s2);
    cout << "Regular: " << first.count() << endl
         << "Make shared: " << second.count() << endl;
    pt1();
    (*sh_ptr1)();
    cout << "As you can see, both are working …Run Code Online (Sandbox Code Playgroud) new-operator ×10
c++ ×8
arrays ×2
memory ×2
c# ×1
constructor ×1
exception ×1
heap ×1
javascript ×1
jquery ×1
jslint ×1
malloc ×1
parsing ×1
stack ×1
struct ×1
value-type ×1