【问题标题】:pointer to instance class containing vector<int> issue指向包含 vector<int> 问题的实例类的指针
【发布时间】:2011-04-16 10:59:39
【问题描述】:

我有这样的课:

class largeInt{
  vector<int> myVector;
  largeInt  operator*  (const largeInt &arg);

}

在我的主要工作中,我在使用指针时无法避免复制:

void main(){

    //this works but there are multiple copies: I return a copy of the calculated
    //largeInt from the multiplication and then i create a new largeInt from that copy.
    largeInt testNum = 10;
    largeInt *pNum = new HugeInt( testNum*10);

    //i think this code avoid one copy but at the end hI points to a largeInt that has
    // myVector = 0 (seems to be a new instance = 0 ). With simple ints this works  great.
    largeInt i = 10;
    largeInt *hI;
    hI = &(i*10);

}

我认为我在矢量设计中缺少/没有管理某些东西.. 我可以实现指针的无副本分配,即使没有实例化一个新的 largeInt? 谢谢各位专家!

【问题讨论】:

    标签: c++ pointers vector copy bigint


    【解决方案1】:

    hI = &amp;(i*10); 获取 temporary largeInt 的地址,该地址在 ';' 之后立即被破坏- 所以hI 指向无效内存。

    当您将两个 largeInt 相乘时,您做会得到一个新实例 - 这就是乘法的作用。也许您打算改用operator*=?这应该修改现有实例而不是创建新实例。

    考虑:

    int L = 3, R = 5;
    
    int j = L*R; // You *want* a new instance - L and R shouldn't change
    L*=R; // You don't want a new instance - L is modified, R is unchanged
    

    另外,您不应该使用new 在堆上创建 largeInt - 只需这样做:

    largeInt i = 10; 
    largeInt hi = i*10; // Create a temporary, copy construct from the temporary
    

    或者:

    largeInt i = 10;
    largeInt hi = i; // Copy construction
    hi *= 10; // Modify hi directly
    

    【讨论】:

    • 或:largeInt hi = 10; 和 hi *= 10;
    猜你喜欢
    • 1970-01-01
    • 2018-12-14
    • 2016-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多